FBFriendModel.find({
id: 333
}, function (err, docs) {
docs.remove(); //Remove all the documents that match!
});
上面的方法似乎不管用。记录还在那里。
有人能修好吗?
FBFriendModel.find({
id: 333
}, function (err, docs) {
docs.remove(); //Remove all the documents that match!
});
上面的方法似乎不管用。记录还在那里。
有人能修好吗?
当前回答
简单的做
FBFriendModel.remove().exec();
其他回答
更新:猫鼬版本(5.5.3)
remove()已弃用,可以使用deleteOne()、deleteMany()或bulkWrite()代替。
至于“mongoose”:“>=2.7.1”,你可以直接用.remove()方法删除文档,而不是找到文档,然后删除它,这在我看来更有效,更容易维护。
看到的例子:
Model.remove({ _id: req.body.id }, function(err) {
if (!err) {
message.type = 'notification!';
}
else {
message.type = 'error';
}
});
更新:
从mongoose 3.8.1开始,有几个方法可以让你直接删除一个文档,比如:
删除 findByIdAndRemove findOneAndRemove
更多信息请参考mongoose API文档。
小心findOne和删除!
User.findOne({name: 'Alice'}).remove().exec();
上面的代码删除了所有名为“Alice”的用户,而不仅仅是第一个用户。
顺便说一下,我更喜欢这样删除文档:
User.remove({...}).exec();
或者提供一个回调函数并省略exec()
User.remove({...}, callback);
这招对我很管用,试试这个:
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
})
});
根据Samyak Jain的回答,我使用异步等待
let isDelete = await MODEL_NAME.deleteMany({_id:'YOUR_ID', name:'YOUR_NAME'});
我更喜欢承诺符号,在这里你需要。
Model.findOneAndRemove({_id:id})
.then( doc => .... )