Delete request in mongodb using _id with nodejs

deleting a row in mongodb doesn't seem to be as easy as it is in SQL lol, but the problem is that I cannot delete the _id row because the _id contains obj ObjectId

that the row is in dB,

{
    "_id" : ObjectId("541ec60e41b46b841adde31e"),
    "name" : "TT"
}

      

and this is how i try to remove it,

db.books.remove({ _id: book_id}, function(err, delete) {
    if(err)
        console.log("ERROR!", err);

    console.log("deleted  ", delete);
});

      

I dont know how to pass book_id

so that the request runs as expected, hopefully you guys can help me find a solution for this. thank!

+3


source to share


2 answers


First convert book_id

to ObjectId

:



var ObjectId = require('mongodb').ObjectID;

...

db.books.remove({ _id: ObjectId(book_id) }, ...);

      

+8


source


var {MongoClient,ObjectID} = require('mongodb');


var url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function(err, db) {
    if(err!=null){
        return console.log(err.message)
    }
  db.collection("App").deleteOne({_id:ObjectID('59c3dfa6d11caa3360af91cc')}, function (err,data) {

       if(err!=null){
            return console.log(err)
        }
        console.log(data);

    });

});

      



0


source







All Articles