Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set retrieve callback in mongoose, in a global variable

I want to set db in global variable, but when I get console name out of findOne function show me undefined, What can I do?

var name;

schema.findone({name : 'Bob'} , function(er , db){
  name = db;
  console.log(db);
});

console.log(name);

thank you.

like image 291
Hossein Marzban Avatar asked Feb 10 '23 23:02

Hossein Marzban


1 Answers

Super classic beginner mistake about asynchronism :)

What's going on :

var name; // FIRST you declare the name variable

schema.findone({name : 'Bob'} , function(er , db){ // SECOND you launch a request to the DB
  name = db; // FOURTH name is populated.
  console.log(db);
});

console.log(name); // !! THIRD !! you log name - it's empty

What you should do :

schema.findone({name : 'Bob'} , function(er , db){
  doSomethingElse(db);
});

function doSomethingElse(name){
    console.log(name); // It's defined.
}

You souldn't even declare a global variable, as it's a bad practice. As soon as the data is available, pass it to another function and do something with it. So you don't pollute your global scope.

Edit : Since you absolutely want a global variable for some reason, then do this :

var name;

schema.findone({name : 'Bob'} , function(er , db){
  name = db;
  console.log(name); // works fine
  doSomethingElse();
});

console.log(name); // name is empty here, because the DB request is still in progress at this stage

function doSomethingElse(){
    console.log(name); // Tadaaaa! It's a global variable and is defined!
}
like image 92
Jeremy Thille Avatar answered Feb 12 '23 13:02

Jeremy Thille