javascript - Mongoose 嵌入式文档对象是 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('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/

相关文章:

javascript - 来自 EventListener 的 ReactJS 事件不会更新 View

javascript - 获取对象数组中键的名称 - JS

javascript - 类型错误 : blur is not a function

javascript - Express Render 无法正常工作返回错误 : No default engine was specified and no extension was provided

node.js - mongodb 匹配和组 2 查询合二为一

javascript - Flowplayer 背景图像未出现

node.js - 如何通过 Node http-proxy记录websocket流量数据

node.js - Mongoose find({}) 不返回任何内容

node.js - Mongoose 不创建索引

javascript - 如何在 express.js 应用程序启动之前加载异步数据库 url 并启动数据库连接?