Reputation: 24583
So I have queried a specific document by id from mongoose. That document has an array of items. This list will always be very small (less than 10 items). I was wondering if there was a way to get a specific item from the array.
Example document:
{
_id: 1,
name: 'some name,
items: [{
id: 23,
name: 'item name 23'
},{
id: 24,
name: 'item name 24'
}]
}
From the mongoose docs I can get the items array:
doc.get('items')
From there I can iterate over the array and find what I want, which is no big deal. Just don't want to reinvent the wheel if this is provided in the framework.
Upvotes: 4
Views: 11696
Reputation: 1984
There is an id method for doing exactly that.
doc.items.id(23)
http://mongoosejs.com/docs/subdocs.html
The solutions using find or findOne will work but involve more code and are more difficult to understand.
Upvotes: 2
Reputation: 3191
I think it will work.
Document.findById({docId, 'items.id': 'yourId'}, {'items.$': 1}, function(err, item){
}
Upvotes: 14