我有以下代码片段,它们在一个项目中嵌入了注释
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中不受支持?
发布于 2012-12-19 00:00:16
你有几个问题:
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
})
})发布于 2012-12-18 23:04:36
您可以像这样定义模式方法:
CommentModel.methods.toJson = { ... };稍后编辑:我指的是一种方法,而不是选项。您还可以过滤此方法中的某些数据,作为额外的好处:)
https://stackoverflow.com/questions/13935432
复制相似问题