Remove record by id?

Why I can't remove record by _id?

Code:

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

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

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

Need Your Help

cmd.exe: when to use call to run external programs

cmd

It seems that a cmd script containing:

mysql create user if not exists

mysql user-management

I have a query to check mysql users list for create new user.