如何使用索引页面上的EJS在Express中循环显示多个模型的数据

时间:2016-11-21 00:17:30

标签: node.js loops express ejs

我有2个模型(Revive和Launch)。我想循环遍历两个并在一个视图上显示数据(index.ejs)

以下是Index:

的路由器
var express = require('express');
var router = express.Router();

var Revive = require('../models/revive');
var Launch = require('../models/launch');

/* GET home page. */
router.get('/', function(req, res, next) {
  Revive.find({}, function (err, revives) {
    if(err) {
      console.log(err)
    } else {
      res.render('pages/index', {revives: revives});
    }
  });
  Launch.find({}, function (err, launches) {
    if(err) {
      console.log(err)
    } else {
      res.render('pages/index', {launches: launches});
    }
  });
});

这是视图(index.ejs):

<% revives.forEach(function(revive) { %>

    <div class="copy">
        <p class="secondary">8.7/10 • Animation, Comedy</p>
        <h3 class="ellipsis"><h4><%= revive.reviveShowName %></h4></h3>
    </div>

<% }); %>

<% launches.forEach(function(launch) { %>

    <div class="copy">
        <p class="secondary">8.7/10 • Animation, Comedy</p>
        <h3 class="ellipsis"><h4><%= launch.launchShowName %></h4></h3>
    </div>

<% }); %>

虽然我只能循环显示一个并且在我添加第二个循环后成功显示但是会抛出标题错误&#39;启动未定义...&#39;

1 个答案:

答案 0 :(得分:0)

针对遇到同一问题的所有人的快速而肮脏的解决方案:

router.get('/', function(req, res, next) {
  Revive.find({}, function (err, revives) {
    if(err) {
      console.log(err)
    } else {
      Launch.find({}, function (err, launches) {
        if(err) {
          console.log(err)
        } else {
          res.render('pages/index', {revives: revives, launches: launches});
        }
      });
    }
  });
});