gpt4 book ai didi

node.js - 将数据传递到 Express 中的 View

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:39 25 4
gpt4 key购买 nike

我正在尝试将查询结果传递到我在 Express 中的 View 。查询是使用 mongodb 进行的,它计算集体用户的总分。

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

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

在我的 ejs View 中指的是 <%= totalpoints %>。下面是我在 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
});

});

有什么想法可以传递查询结果吗?

最佳答案

Node 异步执行查询。即查询的结果不是立即返回的。 您必须等到结果返回并使用回调来完成此操作。因此,渲染页面调用必须在回调内发生。尝试像这样修改您的函数。

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


});

关于node.js - 将数据传递到 Express 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32195310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com