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

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

有人能修好吗?


当前回答

Docs是一个文档数组。所以它没有一个mongoosemmodel .remove()方法。

可以分别迭代和删除数组中的每个文档。

或者—因为看起来您是通过(可能)唯一的id查找文档—使用findOne而不是find。

其他回答

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

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

    });

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

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

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

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

根据Samyak Jain的回答,我使用异步等待

let isDelete = await MODEL_NAME.deleteMany({_id:'YOUR_ID', name:'YOUR_NAME'});

如果你知道文档的_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)

.remove()类似于.find():

MyModel.remove({search: criteria}, function() {
    // removed.
});