Search code examples
node.jsmongodbnode-mongodb-native

Remove record by id?


Why I can't remove record by _id?

Code:

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

Solution

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