Mongoose, find an item in an array of documents

So, I requested a specific document by id from mongoose. This document contains many elements. This list will always be very small (less than 10 items). I was wondering if there is a way to get a specific element from an array.

Example doc: { _id: 1, name: 'some name, items: [{ id: 23, name: 'item name 23' },{ id: 24, name: 'item name 24' }] } 

From mongoose docs, I can get an array of elements:

 doc.get('items') 

From there I can iterate over the array and find what I want, which doesn't really matter. Just do not want to reinvent the wheel, if it is provided for in the framework.

+4
source share
2 answers

I think this will work.

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

There is an id method to do just that.

 doc.items.id(23) 

http://mongoosejs.com/docs/subdocs.html

Solutions using find or findOne will work, but will contain more code and are more difficult to understand.

+1
source

All Articles