在没有存储的情况下在 Sequelize 中创建模型属性

Creating model attributes in Sequelize with no storage

我正在使用 Sequelize 作为我的 ORM。我想创建一个模型,其属性没有关联存储(即没有相应的 table 列)。这些属性可能有getters和setters,也可能有validation。

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

场景

我有一个 LocalLogins 模型。我的模型有 usernamesalt、加盐 password 和未加盐 rawPassword。每次设置 password 时,都会对该值进行加盐和哈希处理。散列的结果成为新密码。原来的"raw"值保存到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.');
    }
  }
});

有一个 DataType.VIRTUAL 正是这样做的:http://docs.sequelizejs.com/en/latest/api/datatypes/#virtual