首先我定义一个model:
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
email: { type:String, required: true}
});
UserSchema.pre('save', function(next){
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
console.log('user.password :',user.password);
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
console.log('hash:',hash);
console.log('user.password :',user.password);
console.log('1')
next();
});
});
next();
});
module.exports = mongoose.model('User', UserSchema);
然后,我在路由里写:
app.post('/sign',function(req,res){
console.log(req.body);
var username = req.body.user,
password = req.body.passwd,
email = req.body.email;
var newUser = new User({
username: username,
password: password,
email: email
});
newUser.save(function(err){
if(err) throw err;
console.log('2')
return res.redirect('/');
});
});
这样保存之后,在mongodb下查询密码还是明文。这个UserSchema.pre('save’,fn)是不是有问题?
console.log出来的是2,1。
我现在知道了是先save后再产生hash。请问我的写法是不是不对?我的理解是save之前先生成 hash,但是实现却不行。