cannot pass id or element to mongoose parameters

Viewed 186

In MongoDB, using mongoose - I tried to delete an item from collection by using findByIdAndDelete() It throws an error -

CastError: Cast to ObjectId failed for value "5f080dd69af4c61774ef447f " at path "_id" for model "Item"

My Mongoose Code -

app.post("/del", function (req, res) {
    const delItem = req.body.del;
    console.log(delItem);           // this one provides the exact id.
    Item.findByIdAndDelete(delItem, function (err) {
        if(err){
            console.log(err);
        }
        else{
            console.log("succesfully Deleted");            
        }
    })
})

I tried find({}) it gives full data, but problem is only when i tried to give value to it like

findById({"_id: delItem}) - it is not working

findById({"_id: "34324jj43j34"}) - if i enter manually it works,

I changed the content of delItems to one item in it then

find({item: delItem}) - not working

find({item: "item 1"}) - working

1 Answers

The problem is that your delItem contains a trailing whitespace which causes this problem: "5f080dd69af4c61774ef447f " - it should be "5f080dd69af4c61774ef447f".

You could do a trim on the value to prevent this error:

Item.findByIdAndDelete(delItem.trim())...
Related