I'm making user authorization system and want to hash password before save it to DB. To reach this i use bcrypt-nodejs. The question in title above;
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
},
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
unique: true,
required: true
}
});
userSchema.pre('save', (next) => {
var user = this;
bcrypt.hash(user.password, bcrypt.genSaltSync(10), null, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
})
});
module.exports = mongoose.model('User', userSchema);