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?
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
})
})
You could define a schema method like this:
CommentModel.methods.toJson = { ... };
Later edit: I am referring to a method, not the options. You could also filter certain data within this method, as a bonus :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.