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.
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With