So i need to create a post request that gets login data(name, email, password) from the user, runs validations, encrypts password, then stores data. The problem is that the encryption function takes time to run, and the variable is still not populated by the time i use it. Tried using another promise-await inside but didn’t work. How do i wait till encryptedPass is not null?
// Bcrypt import, initialize number of rounds of salting
saltRounds = 10;
router.post('/user/create', bodyPraser.json(), async (req, res) => {
// Some code here that runs validations
// Encrypting password
var passwordToEncrypt = req.body.password;
var encryptedPass;
// MongoDB model to store data
const encryptedData = new Model({
fullname: req.body.fullname,
email: req.body.email,
password: encryptedPass
});
// Salting function
bcrypt.genSalt(saltRounds, function (err, salt) {
// Hashing function
bcrypt.hash(passwordToEncrypt, salt, function (err, hash) {
// Store hash in database here
encryptedPass = hash;
});
});
// Save, and store data. Sedn success.
const dataToSave = await encryptedData.save(); // The password is still null at this point
res.status(200).json(dataToSave);
console.log("Data saved");
}
catch (error) {
res.status(400).json({ message: error.message });
console.log("Data not saved!");
}
})
2
Answers
Here’s the modified code. I just put everything under your salt function, because everything depends on salt.
You need to store data in database at the time once the password is hashed and then do it you are doing it before the password is hashed and you are getting the wrong results,
PTR: Also avoid using var instead use let because it’s a bad practice
Do this instead