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)?
You can include both id terms in a single query and the single element projection will still work:
Person.findOne({_id: personId, 'things.id': 2}, {'things.$': 1},
function(err, person) { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With