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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:57:53  来源:igfitidea点击:

Remove record by id?

node.jsmongodbnode-mongodb-native

提问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");
    });
});