如何使用node.js mongoose删除文档?
-
25-10-2019 - |
题
FBFriendModel.find({
id: 333
}, function (err, docs) {
docs.remove(); //Remove all the documents that match!
});
以上似乎不起作用。记录仍然存在。
有人可以修复吗?
解决方案 3
docs
是一系列文档。所以它没有 mongooseModel.remove()
方法。
您可以迭代并分别删除阵列中的每个文档。
或 - 由于看起来您正在通过(可能)唯一ID找到文档 - 使用 findOne
代替 find
.
其他提示
更新:Mongoose版本(5.5.3)
删除()已弃用,您可以使用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';
}
});
更新:
从猫鼬开始 3.8.1
, ,有几种方法可让您直接删除文档,例如:
remove
findByIdAndRemove
findOneAndRemove
参考 Mongoose API文档 了解更多信息。
对我来说,这是3.8.1版本的最好的:
MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});
而且只需要一个DB通话。考虑到您不执行任何操作 remove
搜索和拆除的行动。
简单地做
FBFriendModel.remove().exec();
mongoose.model.find()
返回a 查询对象 还有一个 remove()
功能。
您可以使用 mongoose.model.findOne()
同样,如果您只想删除一个唯一的文档。
否则,您还可以遵循传统方法,然后首先检索文档然后删除。
yourModelObj.findById(id, function (err, doc) {
if (err) {
// handle error
}
doc.remove(callback); //Removes the document
})
以下是开启的方式 model
对象您可以执行以下任何操作以删除文档:
yourModelObj.findOneAndRemove(conditions, options, callback)
yourModelObj.findByIdAndRemove(id, options, callback)
yourModelObj.remove(conditions, callback);
var query = Comment.remove({ _id: id });
query.exec();
remove()
已弃用。利用 deleteOne()
, deleteMany()
或者 bulkWrite()
.
我使用的代码
TeleBot.deleteMany({chatID: chatID}, function (err, _) {
if (err) {
return console.log(err);
}
});
为了概括您可以使用:
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
});
小心findone并删除!
User.findOne({name: 'Alice'}).remove().exec();
上面的代码 删除一切 用户命名为“爱丽丝”而不是 第一个 只要。
顺便说一句,我更喜欢删除这样的文件:
User.remove({...}).exec();
或提供回调并省略exec()
User.remove({...}, callback);
model.remove({title:'danish'}, function(err){
if(err) throw err;
});
如果您只寻找一个要删除的对象,则可以使用
Person.findOne({_id: req.params.id}, function (error, person){
console.log("This object will get deleted " + person);
person.remove();
});
在此示例中,Mongoose将根据匹配的req.params.id删除。
.remove()
像 .find()
:
MyModel.remove({search: criteria}, function() {
// removed.
});
我更喜欢承诺符号,您需要的地方
Model.findOneAndRemove({_id:id})
.then( doc => .... )
为了删除文档,我更喜欢使用 Model.remove(conditions, [callback])
请参阅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();
您可以直接在删除函数中使用查询,因此:
FBFriendModel.remove({ id: 333}, function(err){});
您始终可以使用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;
});
更新: .remove()
被折旧,但这仍然适用于较旧版本
YourSchema.remove({
foo: req.params.foo
}, function(err, _) {
if (err) return res.send(err)
res.json({
message: `deleted ${ req.params.foo }`
})
});
使用remove()方法您可以删除。
getLogout(data){
return this.sessionModel
.remove({session_id: data.sid})
.exec()
.then(data =>{
return "signup successfully"
})
}
这对我有用,只需尝试一下:
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'});
db.collection.remove(<query>,
{
justOne: <boolean>,
writeConcern: <document>
})