Pass data through to the view in Express

我们两清 提交于 2019-12-10 12:44:22

问题


I am trying to pass through the result of a query through to my view in Express. The query is made using mongodb which counts the total points of the collective users.

When I try to pass the count through as a variable, I get

ReferenceError: /Sites/test/views/dashboard.ejs:76

which refers to <%= totalpoints %> in my ejs view. Below is my code in app.js

app.get('/dashboard', function(req, res) {

    User.find({}, function(err, docs) {
        console.log(docs);
    });

    User.find({
        points: {
            $exists: true
        }
    }, function(err, docs) {
        var count = 0;
        for (var i = 0; i < docs.length; i++) {
            count += docs[i].points;
        }
        return count;

        console.log('The total # of points is: ', count);
    });

    var totalpoints = count;

    res.render('dashboard', {
        title: 'Dashboard',
        user: req.user,
        totalpoints: totalpoints
    });

});

Any ideas how I can pass the query result through?


回答1:


Node executes the query asynchronously. That is, the the result of the query is not returned immediately. You have to wait untill the result is returned and callbacks are used to accomplish this.So, the render page call has to happen within the callback. Try modifying your function like this.

app.get('/dashboard', function(req, res) {

  User.find({}, function(err, docs) {
      console.log(docs);
  });

  User.find({
      points: {
          $exists: true
      }
  }, function(err, docs) {
      if(err){
          console.log(err);
          //do error handling
      }
      //if no error, get the count and render it
      var count = 0;
      for (var i = 0; i < docs.length; i++) {
          count += docs[i].points;
      }
      var totalpoints = count;
      res.render('dashboard', {
      title: 'Dashboard',
      user: req.user,
      totalpoints: totalpoints});
  });


});



回答2:


Node.js is asynchronous in nature, res.render will be executed before you get data from the mongoose. Try the following code.

app.get('/dashboard', function(req, res) {

  User.find({}, function(err, docs) {
      console.log(docs);
  });

  User.aggregate({ $group: {
    _id: null,
    count:   { $sum: "$points" }
  }}, function(err, docs) {
        if(err){
            console.log(err);
            //do error handling
        }
        else
          res.render('dashboard', {
          title: 'Dashboard',
          user: req.user,
          totalpoints: docs.count });
      }
  );

});


来源:https://stackoverflow.com/questions/32195310/pass-data-through-to-the-view-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!