问题
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);
回答1:
Below the solution for your problem:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique:true,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
userSchema.pre('save', function() {
console.log(this.password);
this.password = bcrypt.hashSync(this.password);
console.log(this.password);
});
module.exports = mongoose.model('User', userSchema);
Code that I used to run the solution:
exports.create = async function () {
let user = new User({
email : 'test@test.com',
username: 'new username',
password: '123abc'
});
return await user.save()
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
};
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
A common gotcha for beginners is that the unique option for schemas is not a validator. It's a convenient helper for building MongoDB unique indexes. See the FAQ for more information.
来源:https://stackoverflow.com/questions/51291633/node-js-schema-presave-is-not-changing-data