Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are mongoose embedded document objects mongoose objects?

I have the following code snippets which have an embedded comment within an item

var CommentModel = new Schema({
  text: {type: String, required: true},
}, {strict: true})

CommentModel.options.toJSON = { transform: function(doc, ret, options){
  delete ret.__v;
  delete ret._id;
}}

Comment = mongoose.model('Comment', CommentModel);

var ItemModel = new Schema({
  name:        {type: String, required: true},
  comments:    [ Comment ]
}, {strict: true})

Item = mongoose.model('Item', ItemModel);

Item.findOne({}, function (err, item) {
  item.comments.forEach(function(o) {
    console.log(o.toJSON)
  })
})

However it doesn't appear that the resulting array of objects which are returned are mongoose objects or at least that the transformation doesn't get applied. Am i missing something somewhere or is this just not supported in mongoose?

like image 202
Nick Avatar asked Aug 22 '26 06:08

Nick


1 Answers

You've got a couple problems:

ItemModel should reference the schema CommentModel, not the model Comment in its schema:

var ItemModel = new Schema({
  name:        {type: String, required: true},
  comments:    [ CommentModel ]   // <= Here
}, {strict: true})

You need to call toJSON in your console.log, not pass the function as a parameter:

Item.findOne({}, function (err, item) {
  item.comments.forEach(function(o) {
    console.log(o.toJSON())   // <= Here
  })
})
like image 114
JohnnyHK Avatar answered Aug 24 '26 19:08

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!