【问题标题】:Mongoose Object-literal Subdoc Not AccessibleMongoose Object-literal Subdoc 不可访问
【发布时间】:2014-05-21 09:31:57
【问题描述】:

使用 Mongoose,我如何访问数组中的子文档?在架构中,我根据docs 使用对象文字声明了我的子文档。

在我检索到父文档后,我可以注销 doc.children 并查看对象数组,但是当我尝试访问任何文档时,我无法定义。 doc.children 没有作为数组返回,那么如何访问子文档呢?

架构:

var parentSchema = new Schema({
  children: [{ name: 'string' }]
});

用法:

console.log(doc.children);  //[{name: 'hello'}, {name: 'world'}]
doc.children[0];            //undefined
doc.children['0'];          //undefined

【问题讨论】:

    标签: node.js mongodb mongoose subdocument


    【解决方案1】:

    上面的代码看起来几乎和这里的文档一模一样: http://mongoosejs.com/docs/subdocs.html

    我在想你的代码中可能还有其他一些你没有在这里显示的奇怪的东西。也许尝试使用 get:http://mongoosejs.com/docs/api.html#document_Document-get

    doc.get('children')
    

    【讨论】:

    • 好吧,doc.get('children')[0].name;工作......那么这是预期的行为还是我的原始代码也应该工作?
    • 您使用的是旧版本的 mongoose 还是 mongo?
    • Mongoose 3.8.8 和 MongoDB 2.4.9
    猜你喜欢
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多