How can I change, for example, the value of MyVar within the collection.insert function?
Thank you! ;)
The methods you're dealing with are asynchronous.
This means that the code collection.insert
is run, receives a first argument data
, and the second argument is a callback function. This function is not run immediately. It's only rush when BD responds. So the line of code where you have console.log(myVar);
is before than this callback, even though it is in lines of code after that callback.
To solve this problem you have to put all the code that depends on this variable inside the callback, or call code from within the callback by passing this variable myVar
as an argument.
.insert(data, function(err, result){
// correr aqui o código
console.log(result);
});
See if this solves your case:
var sistema = {
variable_bool : false,
acao : function(bool) {
sistema.variable_bool = bool;
},
getBool: function() {
return sistema.variable_bool;
}
};
var action = function(){
sistema.acao(true);
console.log(sistema.getBool());
};
action();
An example:
var ActionsConnection = {
database : null,
myVar : false,
collection: [],
collectionName : "MyCollection",
connectToMongoDB : function() {
this.database.collection(ActionsConnection.collectionName, function(error, collection) {
return collection;
});
},
insertDataOnMongoDB: function(db, data) {
this.database = db;
this.collection = this.connectToMongoDB();
this.collection.insert(data, function(error, result) {
ActionsConnection.setPermission(true);
});
},
setPermission : function(bool) {
this.myVar = bool;
},
getPermission : function() {
return this.myVar;
}
}
ActionsConnection.insertDataOnMongoDB(db, data);
if (ActionsConnection.getPermission() == true) {
console.log('registro cadastrado!');
}