【问题标题】:Creating model attributes in Sequelize with no storage在 Sequelize 中创建没有存储的模型属性
【发布时间】:2015-07-19 18:49:33
【问题描述】:

我使用Sequelize 作为我的 ORM。我想创建一个模型,其属性没有关联的存储(即没有对应的表列)。这些属性可能有 getter 和 setter,也可能有验证。

如何创建不会存储到.save() 磁盘上的实例级属性?

情景

我有一个 LocalLogins 模型。我的模型有一个username、一个salt、一个加盐的password 和一个不加盐的rawPassword。每次设置 password 时,都会对值进行加盐和哈希处理。哈希的结果成为新密码。原始“原始”值保存到rawPassword

我不想存储未加盐的rawPassword,但是只要调用.save(),它就会用于验证。这允许模型需要一定强度的密码。

尝试

我尝试将字段设置为'',但不幸的是没有效果。

var LocalLogin = sequelize.define('LocalLogin', {
  username: {
    allowNull: false,
    field: 'username',
    type: DataTypes.STRING,
  },
  password: {
    allowNull: false,
    field: 'password',
    type: DataTypes.STRING,
  },
  rawPassword: {
    field: '',
    type: DataTypes.STRING
  },
  salt: {
    allowNull: false,
    defaultValue: function() {
      var buf = crypto.randomBytes(32);
      return buf.toString('hex');
    },
    field: 'salt',
    type: DataTypes.STRING,
    }
}, {
  getterMethods: {
    password: function() { return undefined; },
    rawPassword: function() { return undefined; },
    salt: function() { return undefined; }
  },
  setterMethods: {
    password: function(val) {
      // Salt and hash the password
      this.setDataValue('rawPassword', val);
      if(typeof val === 'string')
        this.setDataValue('password', hash(val + this.getDataValue('selt')));
    },
    salt: function(val) {
      // Salt cannot be modified
      return null;
    }
  },
  validate: {
    passwordCheck: function() {
      // Has a new password been set?
      if(this.getDataValue('rawPassword') == null)
        return

      // Did they try to set the password as something other than a string?
      if(typeof this.getDataValue('rawPassword') !== 'string')
        throw new Error('Password must be a string');

      // Make sure the password is long enough
      if(this.getDataValue('rawPassword').length < 6)
        throw new Error('Password must be longer than six characters.');
    }
  }
});

【问题讨论】:

标签: node.js sequelize.js


【解决方案1】:

有一个 DataType.VIRTUAL 可以做到这一点:http://docs.sequelizejs.com/en/latest/api/datatypes/#virtual

【讨论】:

    猜你喜欢
    • 2014-01-05
    • 2017-08-20
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多