Skip to content

Instantly share code, notes, and snippets.

@abernier
Last active June 13, 2021 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abernier/cb0863f6e1b515510fa87520bd854996 to your computer and use it in GitHub Desktop.
Save abernier/cb0863f6e1b515510fa87520bd854996 to your computer and use it in GitHub Desktop.

Using Mongoose pre middleware to systematically hash a User's password

const myuser = new User({
  email: 'jdoe@hotmail.fr',
  password: 'blacky123'
})

myuser.save()
  .then(jdoe => {
    console.log(jdoe.password) // $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
  })
  .catch(console.error)
const userSchema = new Schema({
email: String,
password: String
});
userSchema.pre('save', function (next) {
if (!this.isModified('password')) return next(); // only if password has been modified (or is new)
this.password = bcrypt.hashSync(this.password, 10);
next();
});
userSchema.methods.comparePassword = function (pass, cb) {
bcrypt.compare(pass, this.password, cb);
};
const User = mongoose.model('User', userSchema);
@abernier
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment