I am creating user creation page using mongodb and node. After getting name, email and password, I tried to hash password and save then into mongodb. I could have followed the best practice by using async and await. However I wanted to understand Promise more. So, I tried the following, but at some point I got stuck. Here, used bcrypt for stroing password safely, the steps are 1) bcrypt.getSalt 2) bcrypt.hash 3) create user with new password 4) save it to mongodb. If you look at the following codes, the steps are implemented with those steps. But, when saving user into mongodb, user is out of scope. My question here is how to implement them in the right way with Promise. Could you give me some good example for it? I am beginner programmer, so just want to learn this from expert. so I came to post this.
router.post("/", (req, res, next) => {
bcrypt
.genSalt(10)
.then(salt => {
console.log(`Salt: ${salt}`);
return bcrypt.hash(req.body.password, salt);
})
.then(hash => {
console.log(`Hash: ${hash}`);
return new User({
name: req.body.name,
email: req.body.email,
password: hash
});
})
.then(user => {
console.log(`User: ${user}`);
return User.findOne({ email: user.email }).exec();
})
.then(function(err, found_user) {
if (err) {
return next(err);
}
if (found_user) {
console.log("found user");
} else {
user.save(function(err) {
if (err) {
return next(err);
}
res.redirect(user.url);
});
}
})
.catch(err => console.error(err.message));
});