Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose embedded documents / DocumentsArrays id

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

There is a statement:

DocumentArrays have an special method id that filters your embedded documents by their _id property (each embedded document gets one):

Consider the following snippet:

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

I've looked at the data and there are no _ids for the embedded documents as would appear to be confirmed by this post:

How to return the last push() embedded document

My question is:

Is the documentation correct? If so then how do I find out what 'my_id' is (in the example) to do a '.id(my_id)' in the first place?

If the documentation is incorrect is it safe to use the index as an id within the document array or should I generate a unique Id manually (as per the mentioned post).

like image 611
Lewis Avatar asked Dec 12 '22 05:12

Lewis


1 Answers

Instead of doing push() with a json object like this (the way the mongoose docs suggest):

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

You should create an actual instance of your embedded object and push() that instead. Then you can grab the _id field from it directly, because mongoose sets it when the object is instantiated. Here's a full 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!');
})
like image 116
mpobrien Avatar answered Dec 14 '22 23:12

mpobrien