且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数据传递到Express中的视图

更新时间:2023-12-03 16:09:16

Node异步执行查询.即,查询结果不会立即返回. 您必须等到返回结果并使用回调来完成此操作之后,因此渲染页面调用必须在回调内进行.尝试像这样修改您的功能.

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


});