Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Mongoose "delete" non-existing documents?

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 ? :)

like image 808
Seva Avatar asked May 18 '17 15:05

Seva


1 Answers

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
  }
});
like image 102
Gergo Avatar answered Oct 10 '22 15:10

Gergo