Rajendran S
Rajendran S

Reputation: 21

nodejs mongodb not deleteing based on id

Can you please help me with this code. This code is not deleting the value from MongoDB, while I am running this url : http://localhost:3000/delete/57c6713455a6b92e105c5250.

I am getting this response: {"lastErrorObject":{"n":0},"value":null,"ok":1}, but not deleting .

app.get('/delete/:id', (req, res) => {
   var uid = req.params.id;
   db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
      if (err) return res.send(500, err);
      res.send(result);
   }); 
});

Upvotes: 1

Views: 1987

Answers (3)

Rajendran S
Rajendran S

Reputation: 21

Yes. thank you i figured where i did wrong. see below correct answer.

var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid) }, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
}); 
});

Upvotes: 1

cbass
cbass

Reputation: 2558

In MongoDB you query a document id(_id) by using the ObjectId constructor and not the ObjectId's string. Thus the query needs to be: { '_id': ObjectId(uid) }.

Example

var mongoClient = require('mongodb').MongoClient;    

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

mongoClient.connect("Your connection string", function(err, db) {
   var query = {
      _id: ObjectId("id_string") // Important to notice
   };
   var collection = db.collection('your collection');

   collection.find(query, function(err, docs) {
       console.log(err, docs);
   });
});

Suggestion

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

app.get('/delete/:id', (req, res) => {
   var uid = req.params.id;

   //Add object id to query object
   db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
      if (err) return res.send(500, err);
      res.send(result);
   }); 
});

Upvotes: 6

Nishant
Nishant

Reputation: 3694

This response means, your query is executing properly "OK":1, but the find query is unable to find any doc to delete it.

So before using "findOneAndDelete" use only "findOne" and log the response to check weather you that doc or not.

Upvotes: 0

Related Questions