12
为什么我无法通过_id删除记录?通过ID删除记录?
代码:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
为什么我无法通过_id删除记录?通过ID删除记录?
代码:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
您需要通过_id
值作为对象ID,而不是一个字符串:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});
的MongoDB现在已经打上了删除方法已过时。它已被两个单独的方法取代:deleteOne和deleteMany。
这里是他们相关的入门指南:https://docs.mongodb.org/getting-started/node/remove/
,这里是一个快速的示例:
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");
});
});
它的工作!谢谢) – Sable
是否可以一次删除ID数组? – Denis
@Denis当然,只需使用['$ in'](http://docs.mongodb.org/manual/reference/operator/query/in/#op._S_in):'{_id:{$ in:idsArray} }' – JohnnyHK