Mongodb, getting the identifier of the newly inserted embedded object

I have built-in comments in the message model. I use mongoosejs. After clicking on the new comment in the post, I want to access the ID of the newly added inline comment. Not sure how to get this.

This is what 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 comment identifier is not returned. Note that there is a _id field that is created in db.

The circuit looks like

 var CommentSchema = new Schema({ ... }) var PostSchema = new Schema({ ... comments:[CommentSchema], ... }); 
+4
source share
3 answers

The value of the _id document _id actually assigned by the client, not the server. Thus, the _id new comment is available immediately after the call:

 post.comments.push(comment); 

The attached document post.comments on post.comments will have its _id assigned as it is added, so you can pull it out from there:

 console.log('_id assigned is: %s', post.comments[post.comments.length-1]._id); 
+5
source

_id field is created on the client side, you can get the ID of the embedded document comment.id

Example

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

check in mongo db shell

  > db.stories.findOne() { "title" : "1111", "_id" : ObjectId("5093c6523f0446990e000003"), "comments" : [ { "_id" : ObjectId("5093c65e3f0446990e000004"), "text" : "hi" } ], "__v" : 0 } 
+1
source

You can manually generate _id, then you don’t have to worry about pulling it 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 
0
source

Source: https://habr.com/ru/post/1443648/


All Articles