midhun k midhun k - 11 months ago 61
Node.js Question

Retrieving ID of subdocument after update in mongo db

I wrote a service to push a new data to my collection using update statement and I need to retrieve the id of last inserted data.I am using

for this,but it just giving a response like this:

"result": {
"ok": 1,
"nModified": 1,
"n": 1

My api for that is:

app.post('/feeds',function(req,res) {
var _id = req.body._id;
var title = req.body.title;
var description = req.body.description;
var latitude = Number(req.body.latitude);
var longitude = Number(req.body.longitude);
{_id:_id },
{$push : {
title: title,

},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
else {

This is my mongoose schema:

var user = new mongoose.Schema({

username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{
imageUrl: {type: String}


I want to add data to feed.

my database structure

I want the Id of newly pushed feed.Please help me..

Answer Source

Embedded way (current schema)

If you want to use one document per feed and pushing sub-documents into (embedded way), you can pre-assign a _id to your newly created feed sub-document:

var feedId = new ObjectId();

  _id: _id
}, {
  $push: {
    feed: {
      _id: feedId,
      title: title,
      description: description,
      latitude: latitude,
      longitude: longitude

}, function(err, result) {
  /* ...your code... */

Don't forget to add a index for user.feed._id if you want to query for this field (using ensureIndex orcreateIndex depending of your version).

Using separate collection

As alternative way, you can use a separate feed collection, and use insert statements including a userId foreign key.

You can find more about pro/cons using Multiple Collections vs Embedded Documents here.