FBFriendModel.find({
    id: 333
}, function (err, docs) {
    docs.remove(); //Remove all the documents that match!
});

上面的方法似乎不管用。记录还在那里。

有人能修好吗?


当前回答

如果只寻找一个要删除的对象,则可以使用

Person.findOne({_id: req.params.id}, function (error, person){
        console.log("This object will get deleted " + person);
        person.remove();

    });

在本例中,Mongoose将根据匹配的req.params.id进行删除。

其他回答

Remove()已弃用。使用deleteOne(), deleteMany()或bulkWrite()。

我使用的代码

TeleBot.deleteMany({chatID: chatID}, function (err, _) {
                if (err) {
                    return console.log(err);
                }
            });

如果只寻找一个要删除的对象,则可以使用

Person.findOne({_id: req.params.id}, function (error, person){
        console.log("This object will get deleted " + person);
        person.remove();

    });

在本例中,Mongoose将根据匹配的req.params.id进行删除。

我更喜欢承诺符号,在这里你需要。

Model.findOneAndRemove({_id:id})
    .then( doc => .... )

这对我来说是3.8.1版本最好的:

MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});

它只需要一个DB调用。 如果在搜索和删除之前不执行任何删除操作,则使用此方法。

这招对我很管用,试试这个:

const id = req.params.id;
      YourSchema
      .remove({_id: id})
      .exec()
      .then(result => {
        res.status(200).json({
          message: 'deleted',
          request: {
            type: 'POST',
            url: 'http://localhost:3000/yourroutes/'
          }
        })
      })
      .catch(err => {
        res.status(500).json({
          error: err
        })
      });