-1

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.

2
  • 2
    Does this answer your question? Node JS Asynchronous Database Calls Commented Jul 26, 2021 at 20:35
  • @tbking It doesn't work. I make a callback but it returns empty array. If I make another get request after the first I recieve the array Commented Jul 26, 2021 at 21:38

2 Answers 2

1

Check this way. Hope it should work

  exports.Run =async (req, res) => {
        var response = {}
        var you = "you"
        response[you] = [];
    
        var result = await Model.estimatedDocumentCount().exec(function (err, count) {
            for (let i = 0; i < 8; i++) {
                let random = Math.floor(Math.random() * count)
    
               await Model.findOne()
                    .skip(random)
                    .exec( function (err, result) {
                        response[you].push(result);
                        console.log(response); 
                    })
            }
    return response;
    
            })
           
    console.log(result); // Array is empty here
        res.status(200).send(result);
    };
Sign up to request clarification or add additional context in comments.

1 Comment

No, it doesn't work :( Moreover, I get warning "Void function return value is used" at var result = await Model.estimatedDocumentCount().exec( function (err, count)
0

I found the solution and it works for me:

exports.Run = (req, res) => {
    ex1( function(rp){
        console.log(rp);
        res.status(200).send(rp);
    });
}

function ex1(callback) {
    var response = {}
    var you = "you"
    response[you] = [];
    Model.estimatedDocumentCount().exec(async function (err, count) {
        for (let i = 0; i < 8; i++) {
            let random = Math.floor(Math.random() * count)
            var doc = await Model.findOne().skip(random).exec();
            response[you].push(doc);
        }
        callback(response);
    })

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.