我有以下代码片段,在项目中有嵌入的注释
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)
})
})
但是,返回的结果对象数组似乎不是猫鼬对象,或者至少没有应用转换.我错过了什么地方或者这只是猫鼬不支持吗?
解决方法:
你有几个问题:
ItemModel应引用架构CommentModel,而不是其架构中的模型Comment:
var ItemModel = new Schema({
name: {type: String, required: true},
comments: [ CommentModel ] // <= Here
}, {strict: true})
您需要在console.log中调用toJSON,而不是将该函数作为参数传递:
Item.findOne({}, function (err, item) {
item.comments.forEach(function(o) {
console.log(o.toJSON()) // <= Here
})
})