Change the value of a global variable within a mongoDB function? [closed]

0

How can I change, for example, the value of MyVar within the collection.insert function?

Thank you! ;)

    
asked by anonymous 02.04.2016 / 18:42

2 answers

1

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);
});
    
02.04.2016 / 19:06
0

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!');
}
    
05.04.2016 / 16:49