hedgehog
hedgehog

Reputation: 13

Mongoose bcrypt set password and saving asynchronously

I have a mongoose schema:

UserSchema.methods.setPassword = function (password) {
bcrypt.hash(password, saltRounds).then(function (hash) {
    this.hash = hash;
    }); 
};

and here is how I create the user object:

router.post('/signup', function(req, res, next){
var user = new User();

user.username = req.body.user.username;
user.email = req.body.user.email;
user.setPassword(req.body.user.password);

user.save().then(function(){
  return res.json({user: user.toAuthJSON()});
    }).catch(next);
});

However, it saves the user without the hashed password. I guess it's because the bcrypt.hash callback didn't run before user.save is called. How can I best resolve this issue?

On the bcrypt doc it says not to use bcrypt.hashSync, would it be an appropriate here?

Upvotes: 1

Views: 521

Answers (1)

Abdul Haseeb
Abdul Haseeb

Reputation: 372

UserSchema.methods.setPassword = function (password) {
  return new Promise((resolve, reject) => {
    bcrypt.hash(password, saltRounds, (error, hash) => {
        if (error) {
            reject(error);
        } else {
            this.password = hash;
            resolve(true);
        }
    })
  })
}

and then call

await user.setPassword(req.body.user.password);

or maybe catch the error, idk

Upvotes: 2

Related Questions