Sorry if this sounds silly, I am still learning server-side Javascript. I have this code in my app.js file.
var test;
UserModel.findOne({name: 'guest'}, function(err, user) {
test = user.name;
});
console.log(test);
I understand that this doesn’t work because UserModel.findOne is async and so everything has to happen within the callback. E.g. console.log(test) could execute before the UserModel.findOne finishes.
Question
If I declare var test in my app.js file, is there a way of getting the value of user.name (via UserModel.findOne) into it?
The reason why I am doing this is because I am hoping to retrieve all these information from the database in advance. So that I don’t have to make a database query every time need a user’s name.
If this idea is unsound, are there similar alternatives?
Edit/Update
This isn’t used for authentication/log-in. I intend for all users to have access to the variable test and its content.
Essentially, I am asking why doesn’t the variable test set permanently to user.name but instead only got step within the scope of the callback. And, is it possible to set the variable permanently?
Considering that all users of your app would share that
testvariable, this seems like a bad idea. This is the sort of data you would store in the user’s session if you don’t want to look it up as needed.EDIT
As long as you’re declaring
testat either global or module scope, it is set permanently in thefindOnecallback.