2014-04-08 50 views
2

使用Mongoose時,如何訪問數組中的子文檔?在模式中,我已經按照docs使用對象字面值聲明瞭我的子文檔。Mongoose Object-literal Subdoc Not Accessible

當我檢索到父文檔後,我可以註銷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 

回答

3

上面的代碼看起來幾乎一模一樣的文檔喜歡這裏: http://mongoosejs.com/docs/subdocs.html

我想也許有一些否則在你的代碼行事奇怪你沒有在這裏顯示。也許嘗試使用得到:http://mongoosejs.com/docs/api.html#document_Document-get

doc.get('children') 
+0

那麼,doc.get('children')[0] .name;工程...所以這是預期的行爲還是應該我的原始代碼工作? –

+0

您使用的是mongoose或mongo的舊版本嗎? –

+0

Mongoose 3.8.8和MongoDB 2.4.9 –

相關問題