Im trying to pass the result of the bcrypt hashing function into the user model below.
I can’t seem be able to wrap my head around how to efficiently resolve this promise.
Heres the code:
router.post("/", async (req, res) => {
req.body = sanitize(req.body);
// SHA-256
/* const bitArray = sjcl.hash.sha256.hash(req.body.data[2].value);
const passwordHashed = sjcl.codec.hex.fromBits(bitArray); */
const saltRounds = 10;
const password = req.body.data[2].value;
var passwordHashed;
async function hash() {
return await bcrypt.hash(password, saltRounds, function (err, hash) {});
}
const user = new User({
username: req.body.data[0].value,
email: req.body.data[1].value,
password: hash(),
});
try {
await user.save();
res.status(200).json({ msg: "Success" });
} catch (e) {}
});
That is what I have tried so far, which is probably wrong
>Solution :
Don’t pass a callback to bcrypt.hash and then you can await it.
const user = new User({
username: req.body.data[0].value,
email: req.body.data[1].value,
password: await bcrypt.hash(password, saltRounds),
});