Find after populate mongoose

@Jason Cust explained it pretty well already – in this situation often the best solution is to alter the schema to prevent querying Users by properties of documents stored in separate collection.

Here’s the best solution I can think of that will not force you to do that, though (because you said in the comment that you can’t).

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
  });
});

What we’re doing here is populating only emails matching additional query (match option in .populate() call) – otherwise email field in Users documents will be set to null.

All that’s left is .filter on returned users array, like in your original question – only with much simpler, very generic check. As you can see – either the email is there or it isn’t.

Leave a Comment