0
The methods you’re dealing with are asynchronous.
That means the code collection.insert
is run, takes a first argument data
and the second argument is a callback function. This function is not run immediately. It is run only when the BD responds. So the line of code you have console.log(myVar);
is racing before than this callback, despite being on lines of code after this callback.
To solve this problem you have to put all the code that depends on that variable inside the callback, or call code from inside the callback by passing that variable myVar
as an argument.
.insert(data, function(err, result){
// correr aqui o código
console.log(result);
});
Try to refer to this page: https://docs.mongodb.org/getting-started/node/insert/
– StillBuggin
Welcome(a) to Sopt. Please do not paste screenshots of code. This makes it difficult to search. Also, when placing images, do not omit the description, which is the only way for those who use screen readers understand what has in it.
– Pablo Almeida
First, you declare the variable
var myVar = false;
and then the methoddb.collection(...)
andcollection.insert(...)
must be executed, only then it will be changed. Otherwise, it will remain unchanged. and yet it will be altered internally, and not outside the scope.– Ivan Ferrer