1

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.

2
  • I am not sure if passing a string to coll.remove should work, but I am positive it is far from being efficient even if it does Commented Jun 2, 2014 at 9:52
  • In addition to my above comment. Why should req.body be equal to the _id of your object? Commented Jun 2, 2014 at 9:53

2 Answers 2

3

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
              });
Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.