首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mongoose嵌入文档对象是mongoose对象吗?

mongoose嵌入文档对象是mongoose对象吗?
EN

Stack Overflow用户
提问于 2012-12-18 22:48:23
回答 2查看 1.3K关注 0票数 3

我有以下代码片段,它们在一个项目中嵌入了注释

代码语言:javascript
复制
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中不受支持?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-19 00:00:16

你有几个问题:

ItemModel应该引用模式CommentModel,而不是其模式中的模型Comment

代码语言:javascript
复制
var ItemModel = new Schema({
  name:        {type: String, required: true},
  comments:    [ CommentModel ]   // <= Here
}, {strict: true})

您需要在console.log中调用toJSON,而不是将函数作为参数传递:

代码语言:javascript
复制
Item.findOne({}, function (err, item) {
  item.comments.forEach(function(o) {
    console.log(o.toJSON())   // <= Here
  })
})
票数 5
EN

Stack Overflow用户

发布于 2012-12-18 23:04:36

您可以像这样定义模式方法:

代码语言:javascript
复制
CommentModel.methods.toJson = { ... };

稍后编辑:我指的是一种方法,而不是选项。您还可以过滤此方法中的某些数据,作为额外的好处:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13935432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档