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

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

有人能修好吗?


当前回答

更新:.remove()是贬值的,但这仍然适用于旧版本

YourSchema.remove({
    foo: req.params.foo
}, function(err, _) {
    if (err) return res.send(err)
    res.json({
        message: `deleted ${ req.params.foo }`
    })
});

其他回答

更新:.remove()是贬值的,但这仍然适用于旧版本

YourSchema.remove({
    foo: req.params.foo
}, function(err, _) {
    if (err) return res.send(err)
    res.json({
        message: `deleted ${ req.params.foo }`
    })
});

如果你不喜欢迭代,那就试试

FBFriendModel.find({ id:333 }).remove( callback );

or

FBFriendModel.find({ id:333 }).remove().exec();

find返回一个Query,它有一个remove函数。

更新为Mongoose v5.5.3 - remove()现在已弃用。使用deleteOne(), deleteMany()或findOneAndDelete()代替。

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

你可以随时使用Mongoose内置函数:

var id = req.params.friendId; //here you pass the id
    FBFriendModel
   .findByIdAndRemove(id)
   .exec()
   .then(function(doc) {
       return doc;
    }).catch(function(error) {
       throw error;
    });

对于删除文档,我更喜欢使用Model。(回调)remove(条件)

请参考API文件删除:-

http://mongoosejs.com/docs/api.html#model_Model.remove

对于这种情况,代码将是:-

FBFriendModel.remove({ id : 333 }, function(err, callback){
console.log(‘Do Stuff’);
})

如果你想在不等待MongoDB响应的情况下删除文档,不传递回调,那么你需要对返回的查询调用exec

var removeQuery = FBFriendModel.remove({id : 333 });
removeQuery.exec();