【问题标题】:Send multiple collections to one ejs file using mongodb and nodejs使用 mongodb 和 nodejs 将多个集合发送到一个 ejs 文件
【发布时间】:2021-01-18 13:21:24
【问题描述】:
app.get('/index', function(req, res){            
    Activities.find({}, function(err, activity){
      if(err){
          console.log(err);
      }else{
          res.render('index', {activities:activity});
      }
    });
    Upcoming.find({}, function(err, upcomingActivity){
      if(err){
          console.log(err);
      }else{
          res.render('index', {upcoming:upcomingActivity});
      }
    });
});

我只想获取多个集合的数据,然后将其传递给 index.ejs 文件,以便我可以在那里使用这些数据。 我知道多次使用 res.render() 是行不通的,但是我尝试了很多事情,例如将建立的数据保存到变量,创建这些对象等。但没有 工作。

【问题讨论】:

  • 首先使用这两个结果集创建一个对象,然后将该对象与您的视图一起发送。我希望这能解决问题

标签: node.js mongodb mongoose collections ejs


【解决方案1】:

在您的获取响应中,您应该只在索引页面一起传递参数时呈现。

    app.get('/index', function(req, res){            
        Activities.find({}, function(err, activity){
          if(err){
              console.log(err);
          }else{
                  Upcoming.find({}, function(err, upcomingActivity){
          if(err){
              console.log(err);
          }else{
              res.render('index', {activity:activity, upcoming:upcomingActivity,});
          }
        });
          }
        });
    });

它将以这种方式工作,因为您只有几个集合,但其他方法是将其作为全局对象传递,然后渲染它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多