node.js – 将数据传递到Express中的视图

我试图将查询结果传递给我在Express中的视图.查询是使用 mongodb进行的,mongodb计算集体用户的总点数.

当我尝试将计数作为变量传递时,我得到了

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

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

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

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

    User.find({
        points: {
            $exists: true
        }
    },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
    });

});

我有什么想法可以通过查询结果?

解决方法

Node异步执行查询.也就是说,查询的结果不会立即返回.
您必须等待,直到返回结果并使用回调来完成此操作.因此,渲染页面调用必须在回调中进行.尝试像这样修改你的功能.
app.get('/dashboard',res) {

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

  User.find({
      points: {
          $exists: true
      }
  },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',totalpoints: totalpoints});
  });


});

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...