I'm trying to take some random values from Mongo using mongoose and push it to an array. But the array is empty outside the function:
exports.Run = (req, res) => {
var response = {}
var you = "you"
response[you] = [];
Model.estimatedDocumentCount().exec(function (err, count) {
for (let i = 0; i < 8; i++) {
let random = Math.floor(Math.random() * count)
Model.findOne()
.skip(random)
.exec( function (err, result) {
response[you].push(result);
console.log(response); // Array is increased each iteration
})
}
})
console.log(response); // Array is empty here
res.status(200).send(response);
};
Please, how to fix that?
Thanks in advance.