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
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.
I need to do 4 more queries like this (say teachers, courses etc.) and send them altogether in res.render()
Any help would be appreciated.