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.
I think it will work.
Document.findById({docId, 'items.id': 'yourId'}, {'items.$': 1}, function(err, item){
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With