Embedded documents Mongoose / DocumentsArrays id

See the Mongoose documentation at the following address: http://mongoosejs.com/docs/embedded-documents.html

There is a statement:

DocumentArrays has a special method identifier that filters embedded documents by the _id property (each embedded document receives one):

Consider the following snippet:

post.comments.id(my_id).remove(); post.save(function (err) { // embedded comment with id `my_id` removed! }); 

I looked through the data and there are no _ids for embedded documents, as this post confirms:

How to return the last inline push () document

My question is:

Is the documentation written correctly? If so, then how do I know what is "my_id" (in the example) to do ".id (my_id)" in the first place?

If the documentation is incorrect, it is safe to use the index as an identifier in an array of documents, or I must create a unique identifier manually (according to the specified message).

+4
source share
1 answer

Instead of doing push () with a json object like this (the method suggested by mongoose docs):

 // create a comment post.comments.push({ title: 'My comment' }); 

Instead, you should create the actual instance of your embedded object and push() . Then you can directly capture the _id field, because the mongoose sets it when the object is created. Here is a complete example:

 var mongoose = require('mongoose') var Schema = mongoose.Schema var ObjectId = Schema.ObjectId mongoose.connect('mongodb://localhost/testjs'); var Comment = new Schema({ title : String , body : String , date : Date }); var BlogPost = new Schema({ author : ObjectId , title : String , body : String , date : Date , comments : [Comment] , meta : { votes : Number , favs : Number } }); mongoose.model('Comment', Comment); mongoose.model('BlogPost', BlogPost); var BlogPost = mongoose.model('BlogPost'); var CommentModel = mongoose.model('Comment') var post = new BlogPost(); // create a comment var mycomment = new CommentModel(); mycomment.title = "blah" console.log(mycomment._id) // <<<< This is what you're looking for post.comments.push(mycomment); post.save(function (err) { if (!err) console.log('Success!'); }) 
+12
source

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


All Articles