Code:
function deleteItem(req, res) {
Goods.findByIdAndRemove(req.params.id, (err) => {
if (err) {
res.send({
success: false,
error: err
});
} else {
res.send({
success: true,
item: req.params.id
});
}
})
}
If I pass an _id
of just deleted document - Mongoose successfully "deletes" it.
If I pass an _id
of never existed document, like 591dad9a1583ea0d1065d633
- it also "deletes" it.
Error throws only if pass trash like a34pnv530eargdzbs
.
Could somebody tell me, what's going on, please ? :)
If you check the related Mongoose documentation you will find the reason behind it:
Finds a matching document, removes it, passing the found document (if any) to the callback. http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove
If the document doesn't exist in your database Mongoose wont throw an error. You should check the 2nd parameter of the callback:
Goods.findByIdAndRemove(req.params.id, function(err, doc) {
if(err || !doc) {
// Show an error page
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With