4

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.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
lostintranslation
  • 23,756
  • 50
  • 159
  • 262
  • If you know the position you can use the "dot notation" (e.g. 'items.0') http://docs.mongodb.org/manual/core/read-operations/#arrays – Hector Correa Mar 25 '13 at 19:38
  • I don't want to find by position, I want to find by id. I.E. doc.get('items').find(23); Of course that does not exist just an example of what I am trying to do. – lostintranslation Mar 25 '13 at 20:06
  • I think the solution is posted [here](http://stackoverflow.com/questions/15213089/mongodb-mongoose-find-object-based-on-array-element-return-only-matching-array). – Volox Jul 17 '13 at 07:34

2 Answers2

14

I think it will work.

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

}
Leonardo
  • 3,141
  • 3
  • 31
  • 60
2

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.

naomi
  • 1,934
  • 1
  • 14
  • 29