简体   繁体   English

无法改变这个属性

[英]Can't change property of this

I was trying to create a custom save method so as not to store user passwords as plain text. 我试图创建一个自定义保存方法,以便不将用户密码存储为纯文本。 But it seems whatever I do to change the value of this.values doesn't have any effect. 但似乎无论我做什么来改变this.values的值都没有任何影响。 This is my sequelize model: 这是我的续集模型:

module.exports= function (sequelize, DataTypes){
return sequelize.define("Users",{
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    email: DataTypes.STRING,
    is_admin: DataTypes.BOOLEAN,
    active: DataTypes.BOOLEAN
},{  instanceMethods: {
    user_save: function(){
        if(this.isNewRecord){
            var salt = 'blahblahblah';
            var key128Bits = CyrptoJS.PBKDF2(this.values.password, salt, { keySize: 128/32 });
            delete this.values.password;
            this.values.password = key128Bits.toString()
            console.log('new record ' + key128Bits.toString())
        }
        console.log(this.values)
        this.save();
        return
    }}
  }
);};

the first log statement confirms that the code inside the if isNewRecord is running, and generating a hash, the second log statement and the output indicate that the properties of this remain unchanged from their original values. 第一个日志语句确认if isNewRecord中的代码正在运行,并生成散列,第二个日志语句和输出表明其属性与原始值保持不变。 Does anyone know why this is or how I can fix the problem? 有谁知道为什么这是或如何解决问题?

I could do this immediately after a post request but I'd rather do it this way if possible. 我可以在发布请求后立即执行此操作但我宁愿这样做,如果可能的话。

http://sequelizejs.com/#instances-update-save http://sequelizejs.com/#instances-update-save

set this.password instead of this.values.password 设置this.password而不是this.values.password

The thing is that this.values is actually only a getter which returns all the attributes with its respective values. 问题是this.values实际上只是一个getter,它返回所有属性及其各自的值。 It might be a good idea to add also a setter. 添加一个setter可能是个好主意。 But then there is the question if the setter should update the database or not. 但是问题是,setter是否应该更新数据库。 So basically this.values should only be used for stuff like console.log . 所以基本上this.values应该只用于console.log东西。 Also it's used internally for instance.toJSON() . 它也在内部用于instance.toJSON()

And as XMen already answered correctly, you have to use this.password instead of this.values.password :) 并且由于XMen已经正确回答,你必须使用this.password而不是this.values.password :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM