• A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.

    You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:

    class User extends Model {}
    User.init({
    password_hash: DataTypes.STRING,
    password: {
    type: DataTypes.VIRTUAL,
    set (val) {
    this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
    this.setDataValue('password_hash', this.salt + val);
    },
    validate: {
    isLongEnough (val) {
    if (val.length < 7) {
    throw new Error("Please choose a longer password")
    }
    }
    }
    }
    }, { sequelize });

    VIRTUAL also takes a return type and dependency fields as arguments If a virtual attribute is present in attributes it will automatically pull in the extra fields as well. Return type is mostly useful for setups that rely on types like GraphQL.

    {
    active: {
    type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
    get() {
    return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
    }
    }
    }

    In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.

    Type Parameters

    Parameters

    • ReturnType: T
    • Optional fields: string[]

    Returns DataTypes.VirtualDataType<T>

  • A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.

    You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:

    class User extends Model {}
    User.init({
    password_hash: DataTypes.STRING,
    password: {
    type: DataTypes.VIRTUAL,
    set (val) {
    this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
    this.setDataValue('password_hash', this.salt + val);
    },
    validate: {
    isLongEnough (val) {
    if (val.length < 7) {
    throw new Error("Please choose a longer password")
    }
    }
    }
    }
    }, { sequelize });

    VIRTUAL also takes a return type and dependency fields as arguments If a virtual attribute is present in attributes it will automatically pull in the extra fields as well. Return type is mostly useful for setups that rely on types like GraphQL.

    {
    active: {
    type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
    get() {
    return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
    }
    }
    }

    In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.

    Returns DataTypes.AbstractDataType

Generated using TypeDoc