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)?
source share