germainelol
germainelol

Reputation: 3331

Mongoose .populate with 2 conditions

I have a Team with both hometeam and awayteam variables, I have the code below at the moment to show the name of the hometeam for each match, how would I change this so that I am showing the both the hometeam and awayteam for each match so that it would look something like the following:

[
  "Team 1", "Team 2",
  "Team 3", "Team 4"
]

Where Team 1/2 are in one match and Team 3/4 are in another match for example.

  app.get('/homeTeamNames', function(req, res) {
    util.log('Serving request for url [GET] ' + req.route.path);
    Match.find({}, {'hometeam': 1}).populate('hometeam', {name: 1}).exec(function(err, teams) {
      var homeNames = [];
      for(var i = 0; i < teams.length; i++) {
        homeNames.push(teams[i].hometeam.name);
      }
      res.send(homeNames);
    });
  });

Upvotes: 0

Views: 2164

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can chain multiple populate calls together like this:

Match.find({}, {hometeam: 1, awayteam: 1})
    .populate('hometeam', {name: 1})
    .populate('awayteam', {name: 1})
    .exec(function(err, teams) { ...

Upvotes: 2

Related Questions