我有以下代码片段,它们在项目中嵌入了评论
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)
})
})
但是,返回的结果对象数组似乎不是 Mongoose 对象,或者至少没有应用转换。我是不是在某处遗漏了什么,或者这在 mongoose 中不受支持?
最佳答案
你有几个问题:
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
})
})
关于javascript - Mongoose 嵌入式文档对象是 Mongoose 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13935432/