Documentation
    Preparing search index...

    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. 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.

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

    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.

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

    Type Parameters

    • T

    Hierarchy (View Summary)

    Index
    usageContext: DataTypeUseContext | undefined

    Where this DataType is being used.

    • Escapes a value for the purposes of inlining it in a SQL query. The resulting value will be inlined as-is with no further escaping.

      Parameters

      • value: T

        The value to escape.

      Returns string

    • Called when a value is retrieved from the Database, and its DataType is specified. Used to normalize values from the database.

      Note: It is also possible to do an initial parsing of a Database value using AbstractDialect#registerDataTypeParser. That normalization uses the type ID from the database instead of a Sequelize Data Type to determine which parser to use, and is called before this method.

      Parameters

      • value: unknown

        The value to parse.

      Returns unknown

    • Converts a JS value to a value compatible with the connector library for this Data Type. Unlike escape, this value does not need to be escaped. It is passed separately to the database, which will handle escaping.

      Parameters

      • value: T

        The value to convert.

      Returns unknown