Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove record by id?

Why I can't remove record by _id?

Code:

db.collection('posts', function(err, collection) {
   collection.remove({_id: '4d512b45cc9374271b00000f'});
});
like image 543
Sable Avatar asked Oct 15 '12 18:10

Sable


People also ask

How do I remove a ID from a list in Salesforce?

To delete one Id : List<Id> listId = newList<Id>(); listId. add('0000000000000'); listId.

How do you remove a record?

Press DELETE, select Home > Records > Delete, or press Ctrl+Minus Sign (-).

How do I delete a specific row in PostgreSQL?

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.


2 Answers

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')});
});
like image 72
JohnnyHK Avatar answered Oct 17 '22 06:10

JohnnyHK


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");
    });
});
like image 6
Bill Tarbell Avatar answered Oct 17 '22 07:10

Bill Tarbell