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!
});
上面的方法似乎不管用。记录还在那里。
有人能修好吗?
当前回答
更新:猫鼬版本(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文档。
其他回答
model.remove({title:'danish'}, function(err){
if(err) throw err;
});
裁判:http://mongoosejs.com/docs/api.html # model_Model.remove
更新:.remove()是贬值的,但这仍然适用于旧版本
YourSchema.remove({
foo: req.params.foo
}, function(err, _) {
if (err) return res.send(err)
res.json({
message: `deleted ${ req.params.foo }`
})
});
如果你知道文档的_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)
如果你不喜欢迭代,那就试试
FBFriendModel.find({ id:333 }).remove( callback );
or
FBFriendModel.find({ id:333 }).remove().exec();
find返回一个Query,它有一个remove函数。
更新为Mongoose v5.5.3 - remove()现在已弃用。使用deleteOne(), deleteMany()或findOneAndDelete()代替。
.remove()类似于.find():
MyModel.remove({search: criteria}, function() {
// removed.
});