Nic*_*ick 3 javascript mongoose node.js
我有以下代码片段,在项目中有嵌入的注释
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)
})
})
Run Code Online (Sandbox Code Playgroud)
但是,返回的结果对象数组似乎不是猫鼬对象,或者至少没有应用转换.我错过了什么地方或者这只是猫鼬不支持吗?
你有几个问题:
ItemModel应该引用模式CommentModel,而不是模式Comment中的模型:
var ItemModel = new Schema({
name: {type: String, required: true},
comments: [ CommentModel ] // <= Here
}, {strict: true})
Run Code Online (Sandbox Code Playgroud)
你需要调用toJSON你的console.log,而不是作为参数传递函数:
Item.findOne({}, function (err, item) {
item.comments.forEach(function(o) {
console.log(o.toJSON()) // <= Here
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |