mongodb 通过 id 删除记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12901593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove record by id?
提问by Sable
Why I can't remove record by _id?
为什么我不能通过 _id 删除记录?
Code:
代码:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
回答by JohnnyHK
You need to pass the _idvalue as an ObjectID, not a string:
您需要将_id值作为 ObjectID传递,而不是字符串:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});
回答by Bill Tarbell
MongoDb has now marked the remove method as deprecated. It has been replaced by two separate methods: deleteOne and deleteMany.
MongoDb 现在已将 remove 方法标记为已弃用。它已被两个单独的方法取代:deleteOne 和 deleteMany。
Here is their relevant getting started guide: https://docs.mongodb.org/getting-started/node/remove/
这是他们的相关入门指南:https: //docs.mongodb.org/getting-started/node/remove/
and here is a quick sample:
这是一个快速示例:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')}, function(err, results) {
if (err){
console.log("failed");
throw err;
}
console.log("success");
});
});

