app.post("/delete", (req, res) => {
const deleteItem = req.body.checkbox;
Item.findByIdAndRemove(deleteItem, (err) => {
if (!err) console.log("deleted succesfully");
else console.log(err);
});
res.redirect("/");
});
here deleteItem returns string when console logging, but when I try to deleteItem I get the following error
MongooseError [CastError]: Cast to ObjectId failed for value "61861e5c0bb4650c066f9e60 " at path "_id" for model "Item"
at new CastError (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\error\cast.js:27:11)
at ObjectId.cast (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\schema\objectid.js:158:13)
at ObjectId.SchemaType._castForQuery (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\schematype.js:1088:15)
at ObjectId.castForQuery (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\schema\objectid.js:198:15)
at ObjectId.SchemaType.castForQueryWrapper (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\schematype.js:1045:15)
at cast (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\cast.js:275:32)
at model.Query.Query.cast (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\query.js:3305:12)
at model.Query.Query._castConditions (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\query.js:1295:10)
at model.Query.Query._findOneAndRemove (D:\College\web dev\todolist-v2\node_modules\mongoose\lib\query.js:2251:8)
at D:\College\web dev\todolist-v2\node_modules\kareem\index.js:250:8
at D:\College\web dev\todolist-v2\node_modules\kareem\index.js:23:7
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
stringValue: '"61861e5c0bb4650c066f9e60 "',
kind: 'ObjectId',
value: '61861e5c0bb4650c066f9e60 ',
path: '_id',
reason: undefined,
CodePudding user response:
If you check the exception stack trace:
Cast to ObjectId failed for value "61861e5c0bb4650c066f9e60 "
You have an extra space at the end of the ID. Probably this is the issue, because the argument passed as ObjectID must be a string of 12 bytes or a string of 24 hex characters. In this case it is 25 characters.