将数据传递到Express中的视图 [英] Pass data through to the view in Express

查看:56
本文介绍了将数据传递到Express中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将查询结果传递给Express中的视图.该查询是使用mongodb进行的,它计算了集体用户的总积分.

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

在我的ejs视图中引用<%= totalpoints%>.下面是我在app.js中的代码

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?

推荐答案

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


});

这篇关于将数据传递到Express中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆