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.

2

1 Answer 1

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);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

I know it would work, but i need to do 4 more queries like this say(teachers, coursers, etc) and send them altogether in res.render(). Hope you can understand the situation.
@10ZKhaled Please update that into the question details

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.