Find an object based on an array element, return only the corresponding array element?

I have a Person object in a mongoose, and this person object has several things (each thing has a unique identifier).

person1 = { things[{id: 1, name: 'one'},{id:2, name: 'two'}] } person2 = { things[{id: 3, name: 'three'},{id:4, name: 'four'}] } 

then request:

 Person.findOne({'things.id': 2},{'things.$': 1}, function(err, person) { ... 

This works fine, but I'm looking at all the Person objects (of which there can be many). In this case, I know the identifier of the Person I need, and some unique identifier of the β€œthing”. This is probably much faster to get Person by id:

 Person.findById(personId, function(err, person) { ... 

Then collapse all things to find the right one:

 var thing person.things.forEach(function(t) { if (t.id == thingId) { thing = t; } }); 

I am wondering if there is a better way. I.E. can I query the Person collection by id to get only one Person and then filter out only what I'm looking for (without an ugly loop)?

+6
source share
1 answer

You can include both identifiers in one query, and the projection of one element will work:

 Person.findOne({_id: personId, 'things.id': 2}, {'things.$': 1}, function(err, person) { ... 
+17
source

All Articles