用过mongoose的进来看看什么问题
发布于 11 年前 作者 coolicer 4304 次浏览 最后一次编辑是 8 年前

首先我定义一个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,但是实现却不行。

2 回复

倒数第三行的next去掉试试

是多了一个next,我晕。不知道什么时候打多了一个

回到顶部