0

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.

10ZKhaled
  • 134
  • 6

1 Answers1

1

Mongoose .find returns a promise by chaining .exec to the end,

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.

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);
    }
});
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53