user3802348 user3802348 - 16 days ago 7x
Javascript Question

Function using Mongoose findOne returning undefined?

I'm trying to use Mongoose to pull a random value from a database using Math.random and Mongoose's findOne. Within my function, the value I'm getting is defined; however when I call the function in another class I am receiving an undefined value. I know this is because of Javascript's asynchronous nature, but I'm not sure how to go about fixing this. Any advice would be appreciated!

export const getRandomItem2 = (req, res) => {
var toReturn;
Item.count().exec(function(err, count){

var random = Math.floor(Math.random() * count);
function (err, result) {
toReturn = result.description;
console.log('toReturn populated here!' + toReturn);
return toReturn; //this is returning undefined


It's asynchronous code, so in another function when You call it You should pass callback function to get the result:

export const getRandomItem2 = (callback) => {
      .exec((err, count) => {
          .findOne(Math.floor(Math.random() * count))
          .exec((err, item) => callback(item));

and in some another place:

getRandomItem2(item => {