user3802348
user3802348

Reputation: 2592

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);
    Item.findOne().skip(random).exec(
        function (err, result) {
            toReturn = result.description;
            console.log('toReturn populated here!' + toReturn);
            return toReturn; //this is returning undefined
        });
    });
}

Upvotes: 0

Views: 602

Answers (1)

num8er
num8er

Reputation: 19372

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) => {
    Item
      .count()
      .exec((err, count) => {
        Item
          .findOne(Math.floor(Math.random() * count))
          .skip(skip)
          .exec((err, item) => callback(item));
      });
}

and in some another place:

getRandomItem2(item => {
  console.log(item);
});

Upvotes: 1

Related Questions