Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, find item in a documents array

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.

like image 773
lostintranslation Avatar asked Dec 04 '22 11:12

lostintranslation


2 Answers

I think it will work.

Document.findById({docId, 'items.id': 'yourId'}, {'items.$': 1}, function(err, item){

}
like image 180
Leonardo Avatar answered Dec 28 '22 03:12

Leonardo


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.

like image 31
naomi Avatar answered Dec 28 '22 01:12

naomi