Rohit-Udamale
Rohit-Udamale

Reputation: 11

CastError: in mongoose

app.post("/delete", function (req, res) {
    const checkedId = (req.body.checkBox);
    console.log(checkedId);

    Item.findByIdAndRemove(checkedId, function (err) {
        if (!err) {
            console.log("Successfully deleted");
            redirect("/");
        }
    })
})

I don't know what is wrong with this code but I am getting this error,

CastError: Cast to ObjectId failed for value "63aae09d2679f102298b87b0 " (type string) at path "_id" for model "Item"
    at model.Query.exec (D:\WebDevelopment\EJS\node_modules\mongoose\lib\query.js:4913:21)
    at Query.findOne (D:\WebDevelopment\EJS\node_modules\mongoose\lib\query.js:2616:8)
    at Function.findOne (D:\WebDevelopment\EJS\node_modules\mongoose\lib\model.js:2363:13)
    at Function.findById (D:\WebDevelopment\EJS\node_modules\mongoose\lib\model.js:2309:15)
    at D:\WebDevelopment\EJS\app.js:62:10
    at Layer.handle [as handle_request] (D:\WebDevelopment\EJS\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\WebDevelopment\EJS\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (D:\WebDevelopment\EJS\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (D:\WebDevelopment\EJS\node_modules\express\lib\router\layer.js:95:5)
    at D:\WebDevelopment\EJS\node_modules\express\lib\router\index.js:284:15 {
  messageFormat: undefined,
  stringValue: '"63aae09d2679f102298b87b0 "',
  kind: 'ObjectId',
  value: '63aae09d2679f102298b87b0 ',
  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 (D:\WebDevelopment\EJS\node_modules\bson\lib\error.js:41:28)
      at new ObjectId (D:\WebDevelopment\EJS\node_modules\bson\lib\objectid.js:67:23)

What should I do I want to delete the row having that particular _id, please help I am stuck to this problem and not getting any solution

Upvotes: 1

Views: 61

Answers (1)

NeNaD
NeNaD

Reputation: 20354

Seams that your entry has an extra space in the end: 63aae09d2679f102298b87b0 .

Try to trim the entry before sending it to the function.

Upvotes: 2

Related Questions