Reputation: 1593
Using Mongoose, how do I access a subdocument in an array? In the schema I have declared my subdocument using an object-literal as per the docs.
After I have retrieved the parent document I can log out doc.children and see the array of objects, but when I attempt to access any of the documents I get undefined. doc.children is not returned as an array, so how do I access the subdocuments?
Schema:
var parentSchema = new Schema({
children: [{ name: 'string' }]
});
Usage:
console.log(doc.children); //[{name: 'hello'}, {name: 'world'}]
doc.children[0]; //undefined
doc.children['0']; //undefined
Upvotes: 2
Views: 681
Reputation: 13081
The code above looks almost exactly like the documentation here: http://mongoosejs.com/docs/subdocs.html
I am thinking perhaps there is something else in your code acting strange that you've not displayed here. Perhaps try using get: http://mongoosejs.com/docs/api.html#document_Document-get
doc.get('children')
Upvotes: 3