Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node js-在mongoose pre(';save';…)中散列pwd不会';t存储到数据库_Javascript_Node.js_Mongodb_Hash - Fatal编程技术网

Javascript node js-在mongoose pre(';save';…)中散列pwd不会';t存储到数据库

Javascript node js-在mongoose pre(';save';…)中散列pwd不会';t存储到数据库,javascript,node.js,mongodb,hash,Javascript,Node.js,Mongodb,Hash,当我使用mongoose.pre('save'…)散列我的pwd时,它可以工作,但是数据库中实际存储的值不是散列值。为什么会重置?谢谢 user.password = 'abcd'; UserSchema.pre('save', function(next){ if (!this.isModified('password')) return next(); console.log('this.password: ' + this.password); // returns a

当我使用mongoose.pre('save'…)散列我的pwd时,它可以工作,但是数据库中实际存储的值不是散列值。为什么会重置?谢谢

user.password = 'abcd';

UserSchema.pre('save', function(next){
    if (!this.isModified('password')) return next();

    console.log('this.password: ' + this.password); // returns abcd

    bcrypt.hash(this.password, secret.pwdHashSecret, null, function(err, hash) {
        if(err)
            return next(err);

        this.password = hash;

        console.log('this.password: ' + this.password); // returns hashed pwd

        next();
    });
});

user.save(function(err) {

    console.log('user.password: ' + user.password); // returns abcd???
}

每个函数都有自己的
值。您正在将
password
属性添加到
bcrypt.hash
回调函数的
this
值中。您应该修改外部函数的
值的
密码
属性。一个选项是存储外部函数的
这个
值并在回调中使用它:

UserSchema.pre('save', function(next){
    if (!this.isModified('password')) return next();
    var _this = this;
    console.log('this.password: ' + this.password); // returns abcd

    bcrypt.hash(this.password, secret.pwdHashSecret, null, function(err, hash) {
        if(err)
            return next(err);

        _this.password = hash;

        console.log('this.password: ' + _this.password); // returns hashed pwd

        next();
    });
});