将多个结果插入express.js路由中的req对象

时间:2016-10-27 18:57:03

标签: javascript node.js express elasticsearch

我正在使用ElasticSearch运行Express.js / Node.js应用程序。我试图在同一索引中查看多个类型的结果。我在这里做的是运行搜索查询并根据查询结果执行第二次搜索查询。我可以通过观察node.js控制台看到elasticsearch为玩家返回结果。但是它们没有插入到我的结果对象/数组中。我正在使用快速中间件,因为我必须执行两个搜索并将结果显示为一个。

路由/ index.js

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

function searchPlayer(req, res, next){
  //req.players = [];
  req.teams.forEach(function(team){
    req.body = {searchTerm:team._source.shortName};
    searchModulePlayers.searchPlayers(req.body, function(data){
      req.players.push(data);
      console.log(req.players);
    });
  });
  next();
}

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

我通过阅读post1post2来提出这个解决方案。我可以显示球队阵列。但没有任何东西来自球员阵列。我在这里做错了什么。

1 个答案:

答案 0 :(得分:1)

searchPlayer函数中,next()调用应放在searchPlayers()调用的回调中,基本上就是您为searchTeam()函数所做的操作。

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

正如Talha Awan所建议的,你最好不要在中间件中这样做,而是使用专用的库,比如async one(但还有很多其他的)

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