0

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))

1 Answers1

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

Shivam
  • 3,514
  • 2
  • 13
  • 27