Sable Sable - 2 months ago 14
Node.js Question

Remove record by id?

Why I can't remove record by _id?

Code:

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

Answer

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')});
});