I have this snippet of code, where I am trying to create a new user, bcrypt the password and trying to save the user in the MongoDB through mongoose.
Is there any way I can change this async/await to promise chaining?
user = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
user.password = await bcrypt.hash(user.password, 10);
await user.save();
const token = user.generateAuthToken();
res.header("x-auth-token", token).send({
_id: user._id,
name: user.name,
email: user.email
});
});
You should be able to do something like this:
user = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
bcrypt.hash(user.password, 10)
.then(pw => { user.password = pw; return user.save(); })
.then(() => { ...rest of the function here...});
Try this, with bcrypt salt & hash;
const newUser = new User({
name,
email,
password
});
//Create salt & hash
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save().then(user => {...});
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.