I have a Person object in mongoose, and that person object has multiple things (each thing has a unique ID).
person1 = {
things[{id: 1, name: 'one'},{id:2, name: 'two'}]
}
person2 = {
things[{id: 3, name: 'three'},{id:4, name: 'four'}]
}
then query:
Person.findOne({'things.id': 2},{'things.$': 1}, function(err, person) { ...
This works great but I am searching through all Person objects (which there could be a lot of). In this case I know the id of the Person I need and some unique id of a 'thing'. Its probably a lot faster to get the Person by id:
Person.findById(personId, function(err, person) { ...
Then loop over all the things to find the right one:
var thing
person.things.forEach(function(t) {
if (t.id == thingId) {
thing = t;
}
});
What I am wondering is if there is a better way. I.E. can I query the Person collection by id to get just one Person then filter out just the thing I am looking for (without the ugly loop)?