Problem:
I have a ‘Group’ collection. Each group has an embedded document of ‘Members’. I need to pull out a specific Member by their ‘MemberID’ and fetch all their details from the ‘Users’ collection. I would like to do this using the ‘.populate()’ method but only need to populate that single member’s record not all the members records.
So my query looks like this:
DB.model('groups')
.findById(groupID)
.populate('members._user')
.run(function(err, group){
// then loop over every member and return the one that matches
// the member id we require
});
This seems like a very inefficient way of doing things considering I only need the user details for one member in the group! I only have the memberID not the userID so this is the reason I am going to the members collection.
How can I extract a single member from the embedded ‘members’ document and populate it?
The
populatefunction takes 3 parameters:path,fieldsandconditions.fieldsandconditionsare applied when the referred document(s) is(are) populated via a separate call tomodel.find(...). Try passing topopulatea valid mongodb condition that will only return members that you are interested in.