Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Count the number of documents with mongoose (then also use that info)

So Ive seen a lot of similar questions about counting database entries and I have figured out how to use callback functions to console.log the number, but because of the local scope of that callback I cant figure out how to actually USE that number in another function. I would like to make a random number generator for between 0 and the number of documents in my database. This is what I have so far.

 Comic.countDocuments({}, function (err, count) {
    if (err){
        console.log(err)
    }else{
        console.log(count)
    }
}); 

I would love for it to work like this but it doesnt. Whenever I do it num ends up being a huge amount of metadata instead of a number. Any ideas?

 let num = Comic.countDocuments({}, function (err, count) {
    if (err){
        console.log(err)
    }else{
        return count
    }
});

console.log(Math.floor(Math.random() * num))
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There is no way to return data from async function, because it's async in nature. You can read this answer on SO to better understand how async calls work.

But you can simply it a bit by using async/await

const randomFunction = async() => 
{
  let num = await Comic.countDocuments({});
  console.log(Math.floor(Math.random() * num));
}

Then you can call randomFunction(); wherever you want (as long as it's exported, if using in separate file).

This will console.log the random number

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!