0

Here there is an example code:

//IF I JUST TRY TO CONNECT TO MONGODB
function ConnectToMongo(db) {
    myVar = false;
    db.collection("MyCollection", function(error,collection) { 
        myVar = true;
    });
    console.log(myVar); // RETURN TRUE
}

//IF I TRY TO INSERT DATA
function InsertDataOnMongoDB(db) {
    myVar = false;
    db.collection("MyCollection", function(error,collection) { 
        collection.insert(data, function(error,result){
            myVar = true;
        });
    });
    return myVar; // RETURNS FALSE!!
}

How can I execute the last line line "return myVar" only after collection.insert function ends? I need to return true, in this case.

Thank you!

Seyon
  • 21
  • 1

1 Answers1

2

It displays false because these two functions before console.log are asynchronous. For this reason console.log is executed while db.collection and collection.insert are still executing, so myVar = true; starts when these two operations have finished.

In order to see "true" you have to insert your console.log straight after myVar = true;

This way:

db.collection("MyCollection", function(error, collection){
    collection.insert(data, function(error, result){
        myVar = true;
        console.log(myVar);
    });
});
boxHiccup
  • 128
  • 8