-
-
Save timstermatic/5613771 to your computer and use it in GitHub Desktop.
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); |
All this code is incorrect... you must test if the password was modified before hashing it, or you will double hash it...
userSchema.pre('save', async function(next){
if(this.isModified('password')) this.password = await bcrypt.hash(this.password, 12)
next()
})
myoussef3030 thanks for the great snippet works perfectly.
userSchema.pre('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8)
}
next()
})
for a readability we can also user variable like this
For anybody who might need this for readability and clarity, better to use "isModified" so that when the password is updated, we don't have to re-hash again multiple times.
userSchema.pre("save", async function(next){
if(this.isModified("password")){
this.password = await bcrypt.hash(this.password, 8)
}
next();
});
@exlane, here is the code with async/await