Skip to content Skip to sidebar Skip to footer

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(re

Solution 1:

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.

Solution 2:

The save function returns a WriteResult object which contains as property the id of the added object. view docs, so try to log it like below and see what you get.

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

Post a Comment for "Mongodb - Return Id Of Inserted Item"