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!
});
上面的方法似乎不管用。记录还在那里。
有人能修好吗?
当前回答
概括来说,你可以使用:
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
});
其他回答
如果只寻找一个要删除的对象,则可以使用
Person.findOne({_id: req.params.id}, function (error, person){
console.log("This object will get deleted " + person);
person.remove();
});
在本例中,Mongoose将根据匹配的req.params.id进行删除。
更新:猫鼬版本(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文档。
概括来说,你可以使用:
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
});
Docs是一个文档数组。所以它没有一个mongoosemmodel .remove()方法。
可以分别迭代和删除数组中的每个文档。
或者—因为看起来您是通过(可能)唯一的id查找文档—使用findOne而不是find。
mongodb .model.find()返回一个查询对象,该对象也有一个remove()函数。
如果你只想删除一个唯一的文档,你也可以使用mongoose.model.findOne()。
否则,您也可以遵循传统的方法,即首先检索文档,然后删除。
yourModelObj.findById(id, function (err, doc) {
if (err) {
// handle error
}
doc.remove(callback); //Removes the document
})
以下是在模型对象上您可以执行以下任何操作来删除文档的方法:
yourModelObj.findOneAndRemove(conditions, options, callback)
yourModelObj。findByIdAndRemove(id, options, callback)
yourModelObj。删除(条件,回调);
var query = Comment.remove({ _id: id });
query.exec();