1

I have a query that get user posts and I wish to show only the posts of the Country selected by visitor.

So far I'm trying to do something like this:

  var country = req.query.country || req.session.country || { $ne: '' };
  Posts.find({})
      .populate('_creator')
      .where('_creator.country').equals(country)
      .exec(function(err, posts) {
           console.log(posts);
  });

Unfortunately it doesn't work.

How can I have a query similar to this?

EDIT:

This is the Posts Schema:

var postsSchema = new mongoose.Schema({
    _creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    text: { type: String, default: '' },
    created_at: Date
});
Ayeye Brazo
  • 3,316
  • 7
  • 34
  • 67

1 Answers1

10

You can't include a populated field in your query because populate is executed as a separate query after the initial query completes.

One way to efficiently perform this type of query is to first look up the ids of the users of the selected country and then query for the posts from those users.

// Get the _ids of the users of the selected country.
User.find({country: country}, {_id: 1}, function(err, users) {

    // Map the user docs into an array of just the _ids
    var ids = users.map(function(user) { return user._id; });

    // Get the posts whose _creator is in that set of ids
    Post.find({_creator: {$in: ids}}).populate('_creator').exec(function(err, posts) {
        // posts contains your answer
    });
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471