简体   繁体   中英

findByIdAndRemove not working when using body-parser

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM