0

I want to perform a mongodb request, wait until it end and return a result.

The issue is the instruction after the mongo request looks like to be executed before the request end or even start.

users_opposite = collection.find( {"mode" : opposite} ).forEach(function (usersOpposite) {

    users_closed.push(usersOpposite);
    console.log(users_closed.length);
});
console.log(users_closed.length);
console.log("test");

As a result I'm getting this

0 test 1 2 3 4

How can I say to the following instruction to wait until the foreach is complete ?

Thanks for your help.

Minirock
  • 628
  • 3
  • 13
  • 28
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Orelsanpls May 20 '19 at 13:58

2 Answers2

1

It's not forEach but collection.find needs to complete, then you can get the results in a callback, like:

collection.find({ mode: opposite }, function(err, usersOpposite) {
    console.log(usersOpposite);
});
Greg Herbowicz
  • 1,210
  • 1
  • 17
  • 18
  • Can't make this work. I know I make things bad...I'm getting an error with the following `collection.find({ mode: opposite }, function(err, usersOpposite) { console.log(usersOpposite); }).forEach(function (usersOpposite) { users_closed.push(usersOpposite); console.log(users_closed.length); });` – Minirock May 20 '19 at 14:12
1

You have to wait the execution of collection.find()

// giving a context for the code
async function foo() {

    // something before

    users_opposite = await collection.find( {"mode" : opposite} )
        .forEach(function (usersOpposite) {
            users_closed.push(usersOpposite);
            console.log(users_closed.length);
        });

    console.log(users_closed.length);
    console.log("test");
}

As already suggested by Grégory in the comment, more info here How do I return the response from an asynchronous call?

Andrea Franchini
  • 548
  • 4
  • 14