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);
}
});
4
Answers
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:
Updated code:
Check if below code working!
so i was getting this error -> CastError: Cast to ObjectId failed for value …
check my code below 👇 and see if it helps
I solved the issue by removing blank space in my id ,use
const id = req.params.id
then
const trimmed_id = id.trim()
, passtrimmed_id
on yourfindById
it will work