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);
Below the solution for your problem:
Code that I used to run the solution:
Your first problem is that you can not use arrow function in this type of method: Same Error Solved
Second problem, is that you need to call the bcrypt.hashSync method, if you don‘t want to handle Promises.
And one observation about your schema, all the fields are unique. This attribute unique:true will create a index in the database, and you won't find the user by password. Here the moongose documentation: Moogose Documentation