Javascript mongoose是否嵌入文档对象mongoose对象?
我有以下代码片段,它们在项目中嵌入了注释Javascript mongoose是否嵌入文档对象mongoose对象?,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我有以下代码片段,它们在项目中嵌入了注释 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(
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中不支持这一点?您可以定义如下模式方法:
CommentModel.methods.toJson = { ... };
稍后编辑:
我指的是一种方法,而不是选项。您还可以在此方法中过滤某些数据,作为奖励:)您有几个问题:
ItemModel
应引用架构CommentModel
,而不是其架构中的模型Comment
:
var ItemModel = new Schema({
name: {type: String, required: true},
comments: [ CommentModel ] // <= Here
}, {strict: true})
我认为
toJSON
选项是在模式上设置的,而不是在模型上设置的。这可能是我不可靠的命名约定。设定在模式上。哦,是的,我应该仔细看看。不完全正确。toObject和toJSON具有可以通过这种方式指定的选项。是的,这很有意义(现在适当地重命名了我的对象)。但是我仍然得到“TypeError:Object#has no method'toJSON'”@Nick-Hmm…我确实运行了这段代码并确认它有效。这是Mongoose 3.5.1.Aha是我的错误-我的模型和模式在不同的文件中,我没有导出,所以是的,修复效果很好。谢谢我参考了模型,得到了疏远的错误,谢谢!
Item.findOne({}, function (err, item) {
item.comments.forEach(function(o) {
console.log(o.toJSON()) // <= Here
})
})