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!
});
上面的方法似乎不管用。记录还在那里。
有人能修好吗?
当前回答
我非常喜欢异步/等待功能的Express/Mongoose应用程序中的这种模式:
app.delete('/:idToDelete', asyncHandler(async (req, res) => {
const deletedItem = await YourModel
.findByIdAndDelete(req.params.idToDelete) // This method is the nice method for deleting
.catch(err => res.status(400).send(err.message))
res.status(200).send(deletedItem)
}))
其他回答
概括来说,你可以使用:
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
});
简单的做
FBFriendModel.remove().exec();
对于删除文档,我更喜欢使用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();
model.remove({title:'danish'}, function(err){
if(err) throw err;
});
裁判:http://mongoosejs.com/docs/api.html # model_Model.remove
我非常喜欢异步/等待功能的Express/Mongoose应用程序中的这种模式:
app.delete('/:idToDelete', asyncHandler(async (req, res) => {
const deletedItem = await YourModel
.findByIdAndDelete(req.params.idToDelete) // This method is the nice method for deleting
.catch(err => res.status(400).send(err.message))
res.status(200).send(deletedItem)
}))