I need to save a user in mongodb and after read a saved attribute "usageAcceptance". It should work from the first usage
My algorithmus:
- Im checking if user is in a database
- YES Im saving this user with attribute "usageAcceptance" as false
- NO Im doing nothing go to WelcomeCheck function check
- getCurrentUser().usageAcceptance which is undefined when I start my program for a first time. After that it works
Problem: I think here is a problem:
setCurrentUser(usr);
What to do to be sure that JS execute this command. Because after setting user I'm getting one attribute from it getCurrentUser().usageAcceptance. So my code works but only after second usage. It seems that JS saves my user too slow or not setting my user in a property time. How to be sure that I saved user and after set that method?
My code:
let usr: User = handler.state.session.user;
usr = new userModel();
usr.alexaUserId = sessionUser.userId;
usr.amazonUserId = profile.user_id;
usr.name = profile.name;
userModel.findOne({"amazonUserId": profile.user_id}, (err, doc) => {
if (err) {
console.log("Error: ", err);
}
// in case we don't find the user in our database we continue anyways as we will be lead to the newSession Handler
if (doc) {
console.log("User already in Database: ");
}
if (!doc) {
// I want that new user has always this attribute as false:
usr.usageAcceptance = false;
usr.save(err => {
if (err) {
console.log("Error:", err.message);
} else {
console.log("Saved user in mongoDB.");
}
});
}
});
//here is an error :(
setCurrentUser(usr);
"WelcomeCheck": function () {
console.log(getCurrentUser().usageAcceptance);
if (getCurrentUser().usageAcceptance == false && getCurrentUser().usageAcceptance != undefined) {
this.emit(":ask", "Please accept our intern policy if you want to use this app. Please say yes if you accept it!");
}
else {
this.emit("Welcome");
}
}