Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Return id of inserted item

From following the below tutorial

https://codeforgeek.com/2015/08/restful-api-node-mongodb/

I have the following to create an order in my database

exports.createOrder = function(req,res){
  var db = new mongoOp();
  var response = {};

  db.userId = req.body.userId;
  db.userEmail =  req.body.userEmail;
  db.userOrder = req.body.userOrder;

  db.save(function(err){
      if(err) 
      {
        response = {"error" : true,"message" : "Error adding data"};
      } 
      else 
      {
          response = {"error" : false,"message" : "Data added"};
      }
      res.json(response);
  });

}

How can I return the id of the inserted item from the DB.save() along with the response ?

like image 719
user2085143 Avatar asked Mar 11 '23 14:03

user2085143


1 Answers

The callback function of a db.save() function takes two parameters where the second parameter would give you the inserted or updated result. If you do not provide the _id with the data to be saved, mongodb will generate an id and assign it to the key of _id.

So if you try to get _id from result, you would find something like this: ObjectId("50691737d386d8fadbd6b01d") and you can add it to you your response object.

db.save(function(err, result){
  if(err) {
    response = { error: true, message: "Error adding data" };
  } else {
    response = { error: false, message: "Data added", id: result._id };
  }
  res.json(response);
});

Hope the answer helps you.

like image 83
Sk Arif Avatar answered Mar 21 '23 00:03

Sk Arif