Mayur Arora
Mayur Arora

Reputation: 447

Remove a MongoDB Document using Express JS

I have careted an application that interacts with MongoDb using NodeJS (Express JS). I am trying to remove a document using the "_id" (the one generated by MongoDB). The following piece of code just logs "Deleted Successfully", but does not actuall remove the record:

app.post('/TaskDone', function (req, res) {
    var mongo = require('mongodb'),
        Server = mongo.Server,
        Db = mongo.Db;
    var server = new Server('localhost', 27017, { auto_reconnect: true });
    var database = new Db('pending-list-2', server);
    database.open(function (err, db) {
        if (!err) {
            console.log("Connected for Deletion");
            db.collection('tasks', function (err, coll) {                
                var str = "{_id :"+"ObjectId(" + "\"" + req.body + "\"" + ")" + "}";
               console.log(str);
               coll.remove(str, function (err) {
                   if (err) console.log(err);
                   else console.log("Deleted successfully"); 
                                  }
                    );
            });
        }
    });
});

If I use the MongoDB client and just run db.tasks.remove({_id:ObjectID("idhere")}) , it works. Is there something wrong with the express js code that I have written. I have tried a lot of things but nothing seems to work.

Upvotes: 1

Views: 5679

Answers (2)

Tug Grall
Tug Grall

Reputation: 3520

You must create an ObjectID from the mongodb library:

Also this is expected that you do not have any error. The remove() is executed, but the filter is probably invalid.

So you will have to write something like like:

var mongodb = require('mongodb');
...
...
collection.remove(
            {_id: new mongodb.ObjectID( req.body) }, 
            function (err, result){ 
               //check result to see how many document are deleted
              });

Upvotes: 3

Waqas Ahmed
Waqas Ahmed

Reputation: 493

Try as below:

var id = {
        _id: req.body.id
};

var collection = db.collection("tableName");
collection.remove(id, function(err, records){
        if(err){
            console.log("Error" + err);                
        }
        else{                
            console.log("Omega Job Removed");
        }
    });

Upvotes: -1

Related Questions