How do I solve "CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Task""?

How do I solve "CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Task""?

我对 Node JS 还是个新手。我正在尝试使用 Node JS 和 Mongo DB 创建一个书籍目录。每次我按删除按钮删除一本书时,它都会显示此错误

CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model 
"Task"
BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters

这是我的 server.js:

app.delete("/api/books/:id", async (req, res) => {
try {
  const { id: id } = req.params;
  console.log(id);
  const task = await Task.findOneAndDelete({ _id: id });
  if (!task) {
     return res.status(404).json({ msg: `No task with id :${id}` });
  }
  res.status(200).json(task);
 } catch (error) {
  console.log(error);
 }
});

我也遇到过这个问题。 我收到此错误是因为通过参数传入的 ObjectId 在我的数据库中不存在。因此,这引发了异常。

解决方法:

 //add this line as a check to validate if object id exists in the database or not
 if (!mongoose.Types.ObjectId.isValid(id)) 
            return res.status(404).json({ msg: `No task with id :${id}` });

更新代码:

app.delete("/api/books/:id", async (req, res) => {
try {
  const { id: id } = req.params;
  console.log(id);
  if (!mongoose.Types.ObjectId.isValid(id)) 
      return res.status(404).json({ msg: `No task with id :${id}` 
  });
  const task = await Task.findOneAndDelete({ _id: id });
  res.status(200).json(task);
 } catch (error) {
  console.log(error);
 }
});