Skip to content Skip to sidebar Skip to footer

Inserting Multiple Results To Req Object In Express.js Route

I am running Express.js/Node.js application with ElasticSearch. I am trying to view results from multiple types in the same index. What I do here is run a search query and based th

Solution 1:

In your searchPlayer function, the next() call should be placed inside the callback called by searchPlayers(), basically exactly what you did for the searchTeam() function.

function searchTeam(req, res, next){
  searchModuleTeams.searchTeams(req.body, function(data) {
    req.teams = data;
    next();
  });
}

function searchPlayer(req, res, next){
  req.players = [];                      <--- uncomment this...
  req.teams.forEach(function(team){
    req.body = {searchTerm:team._source.shortName};
    searchModulePlayers.searchPlayers(req.body, function(data){
      req.players.push(data);            <--- ...otherwise this will fail
      next();                            <--- move next() here
    });
  });
}

function renderResults(req, res){
  res.render('index',{
    title:'Search Teams and Players',
    teams:req.teams,
    players:req.players
  });
}

router.post('/search-tp',searchTeam, searchPlayer, renderResults);

And as suggested by Talha Awan, you should preferably not do this in middleware but using a dedicated library, like the async one (but there are tons of others)

import waterfall from 'async/waterfall';

function searchTeam(callback){
  searchModuleTeams.searchTeams(req.body, function(teams) {
    callback(null, teams);
  });
}

function searchPlayer(teams, callback){
  let teamPlayers = [];
  async.each(teams, function(team, teamCallback) {
    let search = {searchTerm: team._source.shortName};
    searchModulePlayers.searchPlayers(search, function(players){
       teamPlayers.push(players);
       teamCallback();
    });
  }, function(err) {
    callback(err, teams, teamPlayers);
  });
}

function renderResults(req, res){
  async.waterfall([
    searchTeam,
    searchPlayer
  ], function (err, teams, players) {
    res.render('index',{
      title:'Search Teams and Players',
      teams: teams,
      players: players
    });
  });
}

router.post('/search-tp', renderResults);

Post a Comment for "Inserting Multiple Results To Req Object In Express.js Route"