[英]How do I get a variable out of a mongodb query in node js?
I want to get a variable out of a mongodb query in node.js which would count the number of documents in a collection named students
我想从node.js中的mongodb查询中获取一个变量,该变量将计算名为
students
的集合中的文档数
I tried to declare a global variable right before the query and tried to assign the value inside the query function: 我试图在查询之前声明一个全局变量,并尝试在查询函数中分配值:
router.get('/dashboard', loggedin, function (req, res, next) {
// Student is a db object of a collection named students
var std_count
Student.find(function(err, doc) {
if(err) console.log(err)
else {
std_count = doc.length
}
})
console.log(std_count)
res.render('dashboard', {
user:req.user
})
});
The console.log()
always prints undefined
, but if I put the console.log()
inside else{}
block, it prints the correct result. console.log()
总是打印undefined
,但是如果我将console.log()
放在else{}
块中,它将打印正确的结果。
I need to do 4 more queries like this (say teachers, courses etc.) and send them altogether in res.render()
我需要再执行4个这样的查询(例如老师,课程等),并将它们一起发送到
res.render()
Any help would be appreciated. 任何帮助,将不胜感激。
Mongoose .find
returns a promise by chaining .exec
to the end, 猫鼬
.find
通过将.exec
链接到最后来返回承诺,
router.get('/dashboard', loggedin, function (req, res, next) {
// Student is a db object of a collection named students
Student.find({})
.exec()
.then(data => {
const std_count = data.length;
res.render('dashboard', {
user:req.user
});
})
.catch(err => res.status(500));
});
Update: 更新:
Then you can use await each query and send them lastly in the res.render
. 然后,您可以使用await每个查询,最后在
res.render
发送它们。
router.get('/dashboard', loggedin, async function (req, res, next) {
try {
const std_count = (await Student.find({}).exec()).length || 0;
const teachers_count = (await Teachers.find({}).exec()).length || 0;
const courses_count = (await Courses.find({}).exec()).length || 0;
return res.render('dashboard', {
user: req.user,
studentCount: std_count,
teacherCount: teachers_count,
coursesCount: courses_count
});
} catch (err) {
return res.status(500);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.