Reputation: 1338
removing a row in mongodb isn't seem to be that easy as in SQL lol, well, my issue is that I cant remove a row by the _id because the _id contains an obj ObjectId
, that's the row in the db,
{
"_id" : ObjectId("541ec60e41b46b841adde31e"),
"name" : "TT"
}
and this is how I'm trying to remove it,
db.books.remove({ _id: book_id}, function(err, delete) {
if(err)
console.log("ERROR!", err);
console.log("deleted ", delete);
});
I've no idea how to pass the book_id
so the query will run as expected,
hope you guys will be able to help me find a solution for this one.
thanks!
Upvotes: 4
Views: 3929
Reputation: 129
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);
});
});
Upvotes: 0
Reputation: 203359
Convert book_id
to an ObjectId
first:
var ObjectId = require('mongodb').ObjectID;
...
db.books.remove({ _id: ObjectId(book_id) }, ...);
Upvotes: 8