I am trying to implement a registration form using bcrypt and nodejs/express.
As you'll see below, I have tried to set User.password = hash;
but for some reason when passing the object into postgres the unhashed password is being input.
The code below shows a minor change. I changed the original
User.create({name, email, password})
to
User.create({name, email, password: hash})
This has worked in passing in the hashed password, but doesn't make sense to me... Shouldn't this not be necessary? What am I missing?
Any help understanding what's going on would be hugely appreciated. Thanks!
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
// Set password to hashed
User.password = hash;
console.log(hash);
// Save user
User.create({
name,
email,
password: hash
})
.then(user => {
res.redirect('/users/login')
})
.catch(err => console.log(err));
}))
Because User
is (I believe) a Mongoose model, similar to a class in ECMAScript 6. Directly assigning properties on the class itself (these are static properties) don't change the created items. What you're doing is creating a new property on the User
variable.
So, all you need to do in order to use the shorthand property notation syntax is make a variable password
equal to hash
:
bcrypt.hash(newUser.password, salt, (err, hash) => {
let password = hash;
User.create(name, email, password)
.then(user => res.redirect("/users/login"))
.catch(err => console.log(err));