最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can Mongoose "delete" non-existing documents? - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked May 18, 2017 at 15:14 SevaSeva 6852 gold badges7 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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./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
  }
});
发布评论

评论列表(0)

  1. 暂无评论