2

I'm using a bcrypt-node and mongoose to hash a users password and save that user to a mongo database. When I debug the code below it appears to be working correctly, when you log the password in the code it shows it hashed, but when you check the database it's still plain text. I'm relatively new to node and mongoose/mongodb so I'm not sure how to troubleshoot. I've tried changing calling next(); to be return next(user); as suggested in another post but that didn't help. Any help would be greatly appreciated.

I'm using node version 6.9.5, mongoose 4.7.0, bcrypt-nodejs 0.0.3 and mongo 3.2.10

 UserSchema.pre('save', function (next) {  
      var user = this;
      if (user.password != "") {
        if (this.isModified('password') || this.isNew) {
          bcrypt.genSalt(10, function (err, salt) {
            if (err) {
          return next(err);
        }
        bcrypt.hash(user.password, salt, null, function(err, hash) {
          if (err) {
            return next(err);
          }
          console.log(hash);
          user.password = hash;
          console.log(user.password);
          next();
        });
      });
    } else {
      return next();
    }
  }
  return next();
});
7
  • Please use consistent and meaningful indentation. Commented Feb 8, 2017 at 23:46
  • Sorry, on my screen, the indentation looks normal. Commented Feb 9, 2017 at 0:51
  • Compare to the code in the answer. Commented Feb 9, 2017 at 13:30
  • @zaph, I understand the sentiment, but perhaps that wasn't the most constructive comment. It comes across as rather condescending. Cheers. Commented Feb 9, 2017 at 19:18
  • The OP sees no indentation issue and the answer is properly indented, that was my point. It is virtually impossible to illustrate indentation in a comment. Commented Feb 9, 2017 at 21:16

1 Answer 1

2

You placed the hash function outside the genSalt() function. Also, you used some nesting and conditionals that made it hard to follow. Try the following and see how it works.

UserSchema.pre('save', function(next) {
  const user = this;
  if (!user.isModified('password')) {
    return next();
  }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, null, (error, hash) => {
      if (error) {
        return next(error);
      }
      console.log('HASH: ', hash);
      user.password = hash;
      console.log('USER.PASSWORD: ', user.password);
      next();
    });
  });
});

A lot more readable, right?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that worked. When seeing your code I was able to see how bad mine looked. To much staring at my code for hours made it hard to see it formatted incorrectly. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.