Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb, getting the id of the newly pushed embedded object

I have embedded comments in a posts model. I am using mongoosejs. After pushing a new comment in a post, I want to access the id of the newly added embedded comment. Not sure how to get it.

Here is how the code looks like.

var post = Post.findById(postId,function(err,post){

   if(err){console.log(err);self.res.send(500,err)}

   post.comments.push(comment);

   post.save(function(err,story){
       if(err){console.log(err);self.res.send(500,err)}
           self.res.send(comment);
   })


});

In the above code, the id of the comment is not returned. Note there is a _id field which is created in the db.

The schema looks like

var CommentSchema = new Schema({
  ...
})

var PostSchema = new Schema({
    ...
    comments:[CommentSchema],
    ...
});
like image 971
Pankaj Avatar asked Nov 02 '12 12:11

Pankaj


People also ask

How do I use $Push in MongoDB?

If the field is absent in the document to update, $push adds the array field with the value as its element. If the field is not an array, the operation will fail. If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push .

What is object ID in mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.

How do you push an object into an array in MongoDB query?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.


3 Answers

A document's _id value is actually assigned by the client, not the server. So the _id of the new comment is available right after you call:

post.comments.push(comment);

The embedded doc pushed to post.comments will have its _id assigned as it's added, so you can pull it from there:

console.log('_id assigned is: %s', post.comments[post.comments.length-1]._id);
like image 98
JohnnyHK Avatar answered Oct 25 '22 00:10

JohnnyHK


You can manually generate the _id then you don't have to worry about pulling it back out later.

var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();

// then set the _id key manually in your object

_id: myId

// or

myObject[_id] = myId

// then you can use it wherever
like image 21
Glenn Avatar answered Oct 25 '22 01:10

Glenn


_id field is generated at client side, you can get the id of the embedded document by comment.id

sample

 > var CommentSchema = new Schema({
     text:{type:String}
  })

 > var CommentSchema = new mongoose.Schema({
     text:{type:String}
 })

 > var Story = db.model('story',StorySchema)
 > var Comment = db.model('comment',CommentSchema)
 > s= new Story({title:1111})
   { title: '1111', _id: 5093c6523f0446990e000003, comments: [] }
 > c= new Comment({text:'hi'})
   { text: 'hi', _id: 5093c65e3f0446990e000004 }
 > s.comments.push(c)
 > s.save()

verify in mongo db shell

    > db.stories.findOne()
{
    "title" : "1111",
    "_id" : ObjectId("5093c6523f0446990e000003"),
    "comments" : [
        {
            "_id" : ObjectId("5093c65e3f0446990e000004"),
            "text" : "hi"
        }
    ],
    "__v" : 0
}
like image 33
RameshVel Avatar answered Oct 25 '22 01:10

RameshVel