I'm trying to crypt the password using bcrypt library in node.js and then store in the database but getting this error. I guess the issue is in the return statement as i'm not able to pass the variable outside the callback. I'm a beginner so little bit confused. Any help would be appreciated.
indes.js
const router = require('express').Router();
const bcrypt = require('bcryptjs/dist/bcrypt');
const User = require('../module/user');
// const bcrypt = require('bcryptjs')
const { registerValidation, loginValidation } = require('../validation')
// Validation
// const joi = require('@hapi/joi');
router.post('/register', async (req, res, err) => {
// Validating data getting form user
registerValidation(req.body)
if (error) {
return res.status(400).send(error.details[0].message)
}
// if user in the database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) {
return res.status(400).send("Email already exist")
}
// Hash password
bcrypt.hash(req.body.password, 10, function (err, hash) {
// Store hash in your password DB.
if (err) {
return res.send(err, 'In hash')
}
// return user.password = hash;
let hashPassword = hash
return hashPassword
});
// Create new user
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashPassword
});
try {
const savedUser = await user.save();
res.send(savedUser);
} catch (err) {
res.status(400).send(err);
}
});
router.get('/test', (req, res, err) => {
if (err) {
console.log('Error', err)
}
res.send('This is test')
})
module.exports = router;