Why I can't remove record by _id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
To delete one Id : List<Id> listId = newList<Id>(); listId. add('0000000000000'); listId.
Press DELETE, select Home > Records > Delete, or press Ctrl+Minus Sign (-).
First, specify the table from which you want to delete data in the DELETE FROM clause. Second, specify which rows to delete by using the condition in the WHERE clause. The WHERE clause is optional. However, if you omit it, the DELETE statement will delete all rows in the table.
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')});
});
MongoDb has now marked the remove method as deprecated. It has been replaced by two separate methods: deleteOne and deleteMany.
Here is their relevant getting started guide: 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");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With