Hello,
There is only a workaround for this case, as the order of query execution happens in the following order.
- Expense documents will be fetched first.
- Populate method will be invoked subsequent to that for each expense document.
- A merge happens as the final step.
A similar case can be found at stack-over-flow. The following text has been quoted from there. The workaround by the them has also been enclosed below.
Mongoose’s populate function doesn’t execute directly in Mongo. Instead after the initial find query returns a set a documents, populate will create an array of individual find queries on the referenced collection to execute and then merge the results back into the original documents. So essentially your find query is attempting to use a property of the referenced document (which hasn’t been fetched yet and therefore is undefined) to filter the original result set.
In this use case it seems more appropriate to store emails as a subdocument array rather than a separate collection to achieve what you want to do. Also, as a general document store design pattern this is one of the use cases that makes sense to store an array as a subdocument: limited size and very few modifications.
The workaround - Example:
Users.find().populate({
path: 'email',
match: {
type: 'Gmail'
}
}).exec(function(err, users) {
users = users.filter(function(user) {
return user.email; // return only users with email matching 'type: "Gmail"' query
});
});
The original discussion:
Thanks
WeDoTheBest4You