Search code examples
javascriptmongodbvariablesvarconsole.log

I cannot reach to variable declared outside of mongodb function


Title says it all I tried it all but variable just returns undefined at console.log

var kategorilerArray;
dbo.collection("anasayfaKategoriler").find().sort(mysort).toArray(function (err, resultKategoriler) {
    if (err) throw err;
    kategorilerArray = resultKategoriler;
    //console.log(kategorilerArray);
});
console.log(kategorilerArray); // > undefined

Solution

  • The reason you are logging undefined is because this is how JS work, meaning that line of code will happen before the kategorilerArray assignment. that line will run before the callback (toArray function receives that callback) and only then the assignment to kategorilerArray will happen.

    you can fix it by adding the kategorilerArray assignment inside the toArray callback function or await the toArray function and then make the assignment.

    This is part of the JS event loop.

    you can read more about it in this article: https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5