Skip to content

Instantly share code, notes, and snippets.

@santosoide
Forked from timstermatic/user.js
Created March 3, 2017 02:27
Show Gist options
  • Save santosoide/83d2c23ccf6965e90ee9eb4135ba8791 to your computer and use it in GitHub Desktop.
Save santosoide/83d2c23ccf6965e90ee9eb4135ba8791 to your computer and use it in GitHub Desktop.
Example of using bcrypt with mongoose middleware to enforce password hashing with bcrypt on save.
var mongoose = require('mongoose'),
Schema = mongoose.Schema
var bcrypt = require('bcrypt')
var UserSchema = new Schema( {
email: String,
password: String
} )
// pre
UserSchema.pre('save', function(next) {
if(this.password) {
var salt = bcrypt.genSaltSync(10)
this.password = bcrypt.hashSync(this.password, salt)
}
next()
})
mongoose.model('User', UserSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment