Home > Enterprise >  How do I solve "CastError: Cast to ObjectId failed for value "undefined" (type string
How do I solve "CastError: Cast to ObjectId failed for value "undefined" (type string

Time:03-20

I am still new to Node JS. I am trying to make a book directory using Node JS and Mongo DB. Every time I press the delete button to delete a book it shows me this error

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

This my 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);
 }
});

CodePudding user response:

I also had this problem once. I got this error because the ObjectId passed in through the params didn't existed in my database. Hence, this threw an exception.

Workaround for this:

 //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}` });

Updated code:

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);
 }
});
  • Related