如何同时查找和显示来自两个 collections 的数据?

How can I find and display data from two collections at the same time?

我正在制作一个节点应用程序,其中存储了两个 collection,我需要遍历每个 collection 的所有文档,然后将其传递给 handlebars 以呈现每个文档。只有一个文档正在呈现,而另一个则没有。我正在使用 express-handlebars 渲染前端。

这里是车把的相关代码:

<div class="tc">
  <ul>
    {{#each drop}}
    <li>{{teamName}} : {{totalScore}} Points <span><i class="fas fa-pen"></i></span></li>
    {{/each}}
  </ul>
  <ul>
    {{#each pass}}
    <li>{{teamName}} : {{totalScore}} Points <span><i class="fas fa-pen"></i></span></li>
    {{/each}}
  </ul>
</div>

我在服务器端尝试了两件事:

1) 错误:设置后无法设置 headers。

app.get('/history', (req, res) => {
  Drop.find()
    .sort({
      totalScore: 'desc'
    })
    .then(drop => {
      res.render('history', {
        hideFooter: false,
        drop: drop
      });
    })
  Pass.find()
    .sort({
      totalScore: 'desc'
    })
    .then(pass => {
      res.render('history', {
        hideFooter: false,
        pass: pass
      });
    })
});

2)前端只渲染Pass,not drop不渲染

app.get('/history', (req, res) => {
  Drop.find()
    .sort({
      totalScore: 'desc'
    })
    .then(drop => {
      Pass.find()
        .sort({
          totalScore: 'desc'
        })
        .then((pass, drop) => {
          res.render('history', {
            hideFooter: false,
            pass: pass,
            drop: drop
          });
        })
    });
});

更新:我也试过 async.parallel

var async = require('async');

async.parallel([
  Drop.find()
  .sort({
    totalScore: 'desc'
  }),
  Pass.find()
  .sort({
    totalScore: 'desc'
  })
], function(results) {
  res.render('history', {
    hideFooter: false,
    pass: pass,
    drop: drop
  });
});

问题可能与您在第二个承诺中添加的 drop 参数有关,请尝试删除它

app.get('/history', (req, res) => {
  Drop.find()
    .sort({
      totalScore: 'desc'
    })
    .then(drop => {
      Pass.find()
        .sort({
          totalScore: 'desc'
        })
        .then(pass => {
          res.render('history', {
            hideFooter: false,
            pass: pass,
            drop: drop
          });
        })
    });
});