Send multiple collections to one ejs file using mongodb and nodejs

Viewed 545
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});
      }
    });
});

I just want to get data of multiple collections and then pass it to index.ejs file so that i can use these data there. I know using res.render() multiple times won't work but i have tried many things like saving founded data to variable , creating an object of these etc. But nothing worked.

2 Answers

In your get response you should render only once the index page passing the parameters all together.

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

It will work this way, since you have only a few collections but other way to do so is passing it as a global object and then rendering it.

Use then to render asynchronously

app.get('/index', (req,res) => {
    Activities.find().then(activity => {
            Upcoming.find().then(upcomingActivity => {
                res.render('index', {Activities: activity, Upcoming: upcomingActivity})
            }).catch(err => console.log(err))
}).catch(err => console.log(err))
})
Related