mercredi 5 octobre 2016

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




Aucun commentaire:

Enregistrer un commentaire