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


i want set db in global variable, when console name out of findone function show me undefined, can do?

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

thank you.

super classic beginner mistake asynchronism :)

what's going on :

var name; // first declare name variable  schema.findone({name : 'bob'} , function(er , db){ // second launch request db   name = db; // fourth name populated.   console.log(db); });  console.log(name); // !! third !! log name - it's empty 

what should :

schema.findone({name : 'bob'} , function(er , db){   dosomethingelse(db); });  function dosomethingelse(name){     console.log(name); // it's defined. } 

you souldn't declare global variable, it's bad practice. data available, pass function , it. don't pollute global scope.

edit : since absolutely want global variable reason, :

var name;  schema.findone({name : 'bob'} , function(er , db){   name = db;   console.log(name); // works fine   dosomethingelse(); });  console.log(name); // name empty here, because db request still in progress @ stage  function dosomethingelse(){     console.log(name); // tadaaaa! it's global variable , defined! } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -