Remove record by id?

Sable picture Sable · Oct 15, 2012 · Viewed 23.6k times · Source

Why I can't remove record by _id?

Code:

db.collection('posts', function(err, collection) {
   collection.remove({_id: '4d512b45cc9374271b00000f'});
});

Answer

JohnnyHK picture JohnnyHK · Oct 15, 2012

You need to pass the _id value as an ObjectID, not a string:

var mongodb = require('mongodb');

db.collection('posts', function(err, collection) {
   collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});