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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With