Change the value of a global variable within a mongoDB function?

Asked

Viewed 754 times

0

inserir a descrição da imagem aqui

How can I change, for example, the Myvar value within the Collection.Insert function?

Thank you! ;)

  • Try to refer to this page: https://docs.mongodb.org/getting-started/node/insert/

  • 2

    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.

  • First, you declare the variable var myVar = false; and then the method db.collection(...) and collection.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.

2 answers

1

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);
});

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!');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.