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

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

有人能修好吗?


当前回答

小心findOne和删除!

  User.findOne({name: 'Alice'}).remove().exec();

上面的代码删除了所有名为“Alice”的用户,而不仅仅是第一个用户。

顺便说一下,我更喜欢这样删除文档:

  User.remove({...}).exec();

或者提供一个回调函数并省略exec()

  User.remove({...}, callback);

其他回答

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

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

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

我使用的代码

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

如果你知道文档的_id,你可以使用findByIdAndDelete(id),这是findOneAndDelete({_id: id})的简写。

import Question from '../models/Question';

const deleteQuestion = (questionId: string) => {
    try {
        Question.findByIdAndDelete(questionId);
    } catch (e) {
        console.error(e);
    }
};

这里的questionId是documentId (_id)

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

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

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

概括来说,你可以使用:

SomeModel.find( $where, function(err,docs){
  if (err) return console.log(err);
  if (!docs || !Array.isArray(docs) || docs.length === 0) 
    return console.log('no docs found');
  docs.forEach( function (doc) {
    doc.remove();
  });
});

实现这一目标的另一种方法是:

SomeModel.collection.remove( function (err) {
  if (err) throw err;
  // collection is now empty but not deleted
});