skip to Main Content

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


  1. 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);
     }
    });
    
    Login or Signup to reply.
  2. Check if below code working!

        if (!mongoose.Types.ObjectId.isValid(id)) {
          throw new HttpException('Not a valid ID!', HttpStatus.NOT_FOUND);
        } else {
          return id;
        }
    
    Login or Signup to reply.
  3. so i was getting this error -> CastError: Cast to ObjectId failed for value …

    1. I log the id out and checked if it corresponded to my id in my Database
    2. since i confirmed it was there and still getting the same error, I then used .trim() method to remove any blank space from the _id and the error was solved

    check my code below 👇 and see if it helps

    const checkItemId = req.body.checkbox;
        console.log(checkItemId);
    
        // find the item by id and remove it make sure youuse .trim to remove any blank space
        Item.findByIdAndRemove(checkItemId.trim(), (err) => {
            if(err){
                console.log(err);
            }else{
                console.log("Removed Succesfull");
            }
        })
    Login or Signup to reply.
  4. I solved the issue by removing blank space in my id ,use const id = req.params.id
    then const trimmed_id = id.trim(), pass trimmed_id on your findById

    it will work

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search