Home > Enterprise >  CastError: Cast to ObjectId failed for value "new" (type string) at path "_id" f
CastError: Cast to ObjectId failed for value "new" (type string) at path "_id" f

Time:06-02

I'm new to Mongoose and am working on a small project in the Web Developer Bootcamp (the one on Udemy) and suddenly ran into this issue with Mongoose. I have a feeling it's actually a really simple fix, but here's the Express routes I have in index.js:

app.get('/products/new', (req, res) => {
    res.render('products/new', { categories });
});

app.post('/products', async (req, res) => {
    const newProduct = await new Product(req, body);
    await newProduct.save();
    res.redirect(`/products/${newProduct._id}`)
})

I didn't include the other routes because they are working fine. Here is new.ejs:

<body>
    <h1>Add A Product</h1>
    <form action="/products" method="post">
        label for="name">Product Name</label>
        <input type="text" name="name" id="name" placeholder="product name">
        <label for="price">Price (Unit)</label>
        <input type="number" id="price" name="price" placeholder="price">
        <label for="category">Select Category</label>
        <select name="category" id="category">
            <% for(let category of categories){ %>
                <option value="<%=category%>">
                    <%=category%>
                </option>
                <% } %>
        </select>
        <button>Submit</button>
    </form>
</body>

When I use the browser to go to localhost:8080/products/new, this error comes up in the terminal:

/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/query.js:4719
  const castError = new CastError();
                    ^

CastError: Cast to ObjectId failed for value "new" (type string) at path "_id" for model "Product"
    at model.Query.exec (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/query.js:4719:21)
    at model.Query.Query.then (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/query.js:4818:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  messageFormat: undefined,
  stringValue: '"new"',
  kind: 'ObjectId',
  value: 'new',
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
      at new BSONTypeError (/home/christian-js/Code/MongoExpress/node_modules/bson/lib/error.js:41:28)
      at new ObjectId (/home/christian-js/Code/MongoExpress/node_modules/bson/lib/objectid.js:67:23)
      at castObjectId (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/cast/objectid.js:24:12)
      at ObjectId.cast (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/schema/objectid.js:245:12)
      at ObjectId.SchemaType.applySetters (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/schematype.js:1189:12)
      at ObjectId.SchemaType._castForQuery (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/schematype.js:1623:15)
      at ObjectId.SchemaType.castForQuery (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/schematype.js:1613:15)
      at ObjectId.SchemaType.castForQueryWrapper (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/schematype.js:1590:20)
      at cast (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/cast.js:344:32)
      at model.Query.Query.cast (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/query.js:5141:12),
  valueType: 'string'
}

Like I said, I'm new to Mongoose so I don't know what to do. I hope I added enough detail but I will update this question if not.

CodePudding user response:

Try this:

const newProduct = await new Product(req.body).save()
res.redirect(`/products/${newProduct._id}`)

Seems you are having trouble with your arguments when creating a new Product.

  • Related