我需要在mongodb中保存用户并在读取保存的属性" usageAcceptance"之后。它应该从第一次使用
开始工作我的算法:
问题: 我认为这是一个问题:
setCurrentUser(usr);
如何确保JS执行此命令。因为在设置用户之后我从它获取一个属性getCurrentUser()。usageAcceptance。所以我的代码工作,但只在第二次使用后。似乎JS保存我的用户太慢或没有在属性时间设置我的用户。如何确保我保存用户并设置该方法后?
我的代码:
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");
}
}