如何使用 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
最佳答案
上面的代码看起来几乎和这里的文档一模一样: http://mongoosejs.com/docs/subdocs.html
我在想,也许您的代码中还有一些您没有在此处显示的奇怪行为。也许尝试使用 get:http://mongoosejs.com/docs/api.html#document_Document-get
doc.get('children')
关于node.js - Mongoose 对象文字子文档不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22941237/