Skip to content

Model, attribute and association options ​

Options of Model.init, sequelize.define, @Table / @Column, attribute definitions, validation and associations.

Options marked postgrelize extension exist only in postgrelize; Sequelize v6 has no such option. This page is generated from the TypeScript declarations and their TSDoc, so it always matches the code.

InitOptions ​

Options of Model.init: table-level options plus hooks, scopes and validation. Extends DefinitionOptions.

See also: Model.init.

ts
User.init(
  { name: DataTypes.STRING, email: DataTypes.STRING },
  {
    sequelize,
    modelName: 'User',
    paranoid: true,
    defaultScope: { where: { active: true } },
    scopes: { admins: { where: { role: 'admin' } } },
  },
);
OptionTypeDescription
timestampsbooleanAdd createdAt / updatedAt. Default true.
underscoredbooleanUse snake_case column names for attributes and the table name.
freezeTableNamebooleanUse the model name as table name without pluralization.
schemastringPostgreSQL schema of the tables.
paranoidbooleanSoft-delete rows (deletedAt) instead of deleting them.
hooksPartial<Readonly<Record<"beforeValidate" | "afterValidate" | "validationFailed" | "befo…Hooks added to every model. Lifecycle hooks, by hook name.
modelNamestringModel name. Defaults to the class name.
nameReadonly<{ singular?: string | undefined; plural?: string | undefined; }>Singular and plural model name (Sequelize v6 ModelOptions.name). Drives the default alias and foreign key of belongsTo / hasOne / hasMany / belongsToMany and the accessor names. A missing form falls back to the inflection of modelName.
tableNamestringTable name. Defaults to the pluralized model name.
schemaDelimiterstringSeparator between schema and table that getTableName reports (PostgreSQL always uses . in SQL).
createdAtstring | booleanName of the created-at attribute, or false to disable it. Default: 'createdAt'.
updatedAtstring | booleanName of the updated-at attribute, or false to disable it. Default: 'updatedAt'.
deletedAtstring | booleanName of the deleted-at attribute of paranoid models. Default: 'deletedAt'.
versionstring | booleanOptimistic locking: true adds a version attribute, a string names it.
indexesreadonly Readonly<{ fields?: readonly IndexField[] | undefined; name?: string | undefin…Indexes created by sync().
commentstringTable comment.
unlogged postgrelize extensionbooleanCREATE UNLOGGED TABLE on sync: faster writes, no WAL, emptied after a crash, not replicated. PostgreSQL extension.
temporary postgrelize extensionbooleanCREATE TEMPORARY TABLE on sync: lives as long as the database session; cannot have a schema. See QueryInterface.createTable. PostgreSQL extension.
sequelizeRuntimeOwnerOwning Sequelize instance.
defaultScopeReadonly<Record<string, unknown>>Scope applied to every query unless unscoped() / scope() is used.
scopesReadonly<Record<string, ScopeDefinition>>Named scopes: options or functions returning options.
whereMergeStrategyWhereMergeStrategyHow where of merged scopes combine: 'overwrite' replaces same keys, 'and' joins them with Op.and. Default: 'overwrite'.
validateReadonly<Record<string, ModelValidatorFunction>>Model-level validators; throw to fail.
validationSchema postgrelize extensionReadonly<{ '~standard': Readonly<{ version: 1; vendor: string; validate: (value: unknow…Standard Schema (zod, valibot, arktype) validating all attribute values. postgrelize extension; schema keeps its v6 meaning (PostgreSQL schema).

DefineOptions ​

Options of sequelize.define: the model options of Model.init without sequelize.

ts
const options: DefineOptions = { tableName: 'products', timestamps: false, paranoid: false };
const Product = sequelize.define('Product', { sku: DataTypes.STRING }, options);
OptionTypeDescription
timestampsbooleanAdd createdAt / updatedAt. Default true.
underscoredbooleanUse snake_case column names for attributes and the table name.
freezeTableNamebooleanUse the model name as table name without pluralization.
schemastringPostgreSQL schema of the tables.
paranoidbooleanSoft-delete rows (deletedAt) instead of deleting them.
hooksPartial<Readonly<Record<"beforeValidate" | "afterValidate" | "validationFailed" | "befo…Hooks added to every model. Lifecycle hooks, by hook name.
modelNamestringModel name. Defaults to the class name.
nameReadonly<{ singular?: string | undefined; plural?: string | undefined; }>Singular and plural model name (Sequelize v6 ModelOptions.name). Drives the default alias and foreign key of belongsTo / hasOne / hasMany / belongsToMany and the accessor names. A missing form falls back to the inflection of modelName.
tableNamestringTable name. Defaults to the pluralized model name.
schemaDelimiterstringSeparator between schema and table that getTableName reports (PostgreSQL always uses . in SQL).
createdAtstring | booleanName of the created-at attribute, or false to disable it. Default: 'createdAt'.
updatedAtstring | booleanName of the updated-at attribute, or false to disable it. Default: 'updatedAt'.
deletedAtstring | booleanName of the deleted-at attribute of paranoid models. Default: 'deletedAt'.
versionstring | booleanOptimistic locking: true adds a version attribute, a string names it.
indexesreadonly Readonly<{ fields?: readonly IndexField[] | undefined; name?: string | undefin…Indexes created by sync().
commentstringTable comment.
unlogged postgrelize extensionbooleanCREATE UNLOGGED TABLE on sync: faster writes, no WAL, emptied after a crash, not replicated. PostgreSQL extension.
temporary postgrelize extensionbooleanCREATE TEMPORARY TABLE on sync: lives as long as the database session; cannot have a schema. See QueryInterface.createTable. PostgreSQL extension.
defaultScopeReadonly<Record<string, unknown>>Scope applied to every query unless unscoped() / scope() is used.
scopesReadonly<Record<string, ScopeDefinition>>Named scopes: options or functions returning options.
whereMergeStrategyWhereMergeStrategyHow where of merged scopes combine: 'overwrite' replaces same keys, 'and' joins them with Op.and. Default: 'overwrite'.
validateReadonly<Record<string, ModelValidatorFunction>>Model-level validators; throw to fail.
validationSchema postgrelize extensionReadonly<{ '~standard': Readonly<{ version: 1; vendor: string; validate: (value: unknow…Standard Schema (zod, valibot, arktype) validating all attribute values. postgrelize extension; schema keeps its v6 meaning (PostgreSQL schema).

AttributeOptions ​

Column definition of a model attribute (Sequelize v6 ModelAttributeColumnOptions). sync() turns these into CREATE TABLE column definitions; validators run before INSERT / UPDATE.

See also: Model.init.

ts
const attr: AttributeOptions = {
  type: DataTypes.STRING,
  allowNull: false,
  unique: true,
  validate: { isEmail: true },
};
OptionTypeDescription
typeDataTypeInputColumn type; a DataTypes entry or its factory call.
allowNullbooleanWhether NULL is allowed. Default: true.
defaultValue{}Default value: a literal value, an expression, DataTypes.NOW / DataTypes.UUIDV4, or a function called once per new row (client-side only, never part of the DDL).
primaryKeybooleanPart of the primary key. Without any primary key, an id attribute is added. Default: false.
autoIncrementbooleanGenerated by a sequence (SERIAL, or an identity column with identity). Default: false.
identity postgrelize extension"always" | "byDefault"GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY instead of SERIAL. PostgreSQL extension.
generated postgrelize extensionReadonly<{ as: unknown; stored?: boolean | undefined; }>Generated column GENERATED ALWAYS AS (expression) STORED; never written by INSERT/UPDATE. PostgreSQL extension.
fieldstringColumn name, if different from the attribute name. Default: the attribute name.
uniquestring | boolean | Readonly<{ name?: string | undefined; msg?: string | undefined; null…Unique constraint: true, a constraint name, or { name, msg }.
commentstringColumn comment (COMMENT ON COLUMN) written by sync().
valuesreadonly string[]Allowed values of an ENUM column declared with the bare type, { type: DataTypes.ENUM, values: ['a', 'b'] } (Sequelize v6). Ignored for other types.
referencesstring | Readonly<{ model: string | Readonly<{ tableName: string; schema?: string | und…Foreign key reference.
onDeletestringON DELETE action of the foreign key, e.g. 'CASCADE'; needs references.
onUpdatestringON UPDATE action of the foreign key, e.g. 'CASCADE'; needs references.
validateReadonly<Record<string, unknown> & { schema?: Readonly<{ '~standard': Readonly<{ versio…Validators run before INSERT / UPDATE.
get(this: M) => unknownCustom getter, called with the model instance as this.
set(this: M, value: unknown) => voidCustom setter, called with the model instance as this.

ReferenceOptions ​

Foreign key target of an attribute.

ts
const ref: ReferenceOptions = { model: 'Users', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED };
OptionTypeDescription
modelstring | Readonly<{ tableName: string; schema?: string | undefined; }> | Readonly<{ get…Referenced table name, an object with the table name and schema, or the referenced model class (its table name is read when the DDL is built).
keystringReferenced column. Default: primary key.
deferrableReadonly<{ sql: string; }>Deferrable mode of the foreign key constraint.

UniqueOptions ​

Named unique constraint of an attribute. Give several attributes the same name to form one composite unique key.

ts
const email: UniqueOptions = { name: 'users_email_unique', msg: 'Email already taken', nullsNotDistinct: true };
OptionTypeDescription
namestringConstraint name; attributes with the same name form a composite unique key.
msgstringValidation message used when the constraint is violated.
nullsNotDistinct postgrelize extensionbooleanUNIQUE NULLS NOT DISTINCT: treat NULLs as equal. PostgreSQL extension.

ValidateOptions ​

Options of instance.validate(). Validation throws ValidationError when an attribute is invalid.

See also: Model.validate.

ts
const opts: ValidateOptions = { skip: ['password'], hooks: false };
await user.validate(opts);
OptionTypeDescription
hooksbooleanRun beforeValidate / afterValidate / validationFailed hooks. Default: true.
skipreadonly string[]Attributes to skip.
fieldsreadonly string[]Only validate these attributes.

AttributeValidateOptions ​

Attribute validate option: Sequelize v6 built-in validators (validator.js names plus is, not, len, notEmpty, min, max, ...), custom functions, and schema — any Standard Schema (zod, valibot, arktype; PostgreSQL-independent extension).

ts
const validate: AttributeValidateOptions = {
  isEmail: true,
  len: { args: [3, 120], msg: 'Email must be 3-120 characters' },
  noGmail(value: unknown) {
    if (String(value).endsWith('@gmail.com')) throw new Error('Gmail is not allowed');
  },
};
OptionTypeDescription
schemaReadonly<{ '~standard': Readonly<{ version: 1; vendor: string; validate: (value: unknow…Standard Schema the value must satisfy.
notNullboolean | Readonly<{ args?: unknown; msg?: string | undefined; }>Custom message for allowNull: false violations.

ModelNameOptions ​

Singular and plural forms of a model name (Sequelize v6 ModelNameOptions).

ts
const name: ModelNameOptions = { singular: 'person', plural: 'people' };
OptionTypeDescription
singularstringSingular model name.
pluralstringPlural model name.

AssociationOptions ​

Options shared by all association methods (Sequelize v6 AssociationOptions). Used by hasOne, hasMany, belongsTo and (extended) belongsToMany.

See also: Model.hasMany.

ts
const opts: AssociationOptions = {
  as: 'posts',
  foreignKey: { name: 'authorId', allowNull: false },
  onDelete: 'CASCADE',
};
User.hasMany(Post, opts);
OptionTypeDescription
asstring | Readonly<{ singular: string; plural: string; }>Alias: string, or { singular, plural } for multi associations. Default: the target model name.
foreignKeystring | Readonly<{ name?: string | undefined; field?: string | undefined; allowNull?: …Foreign key attribute name or options.
sourceKeystringAttribute of the source referenced by the foreign key (hasOne / hasMany / belongsToMany).
targetKeystringAttribute of the target referenced by the foreign key (belongsTo / belongsToMany).
scopeReadonly<Record<string, unknown>>Attribute values applied to associated rows (filter on read, values on write).
constraintsbooleanCreate foreign key constraints on sync(). Default: true.
onDeletestringON DELETE action of the foreign key constraint, e.g. 'CASCADE'.
onUpdatestringON UPDATE action of the foreign key constraint, e.g. 'CASCADE'.
hooksbooleanSequelize v6 hooks flag. With onDelete: 'CASCADE' and hooks: true, destroying an instance first loads its associated rows and destroys each of them with its own hooks (beforeDestroy, afterDestroy), then deletes the instance; without the flag PostgreSQL cascades the delete and no hooks of the target run. Only a real delete cascades this way, not the soft delete of a paranoid model.

BelongsToManyOptions ​

Options of belongsToMany. Extends AssociationOptions; foreignKey is the junction column pointing at the source, otherKey the one pointing at the target.

See also: Model.belongsToMany.

ts
const opts: BelongsToManyOptions = { through: 'ProjectTask', foreignKey: 'projectId', otherKey: 'taskId' };
Project.belongsToMany(Task, opts);
OptionTypeDescription
asstring | Readonly<{ singular: string; plural: string; }>Alias: string, or { singular, plural } for multi associations. Default: the target model name.
foreignKeystring | Readonly<{ name?: string | undefined; field?: string | undefined; allowNull?: …Foreign key attribute name or options.
sourceKeystringAttribute of the source referenced by the foreign key (hasOne / hasMany / belongsToMany).
targetKeystringAttribute of the target referenced by the foreign key (belongsTo / belongsToMany).
scopeReadonly<Record<string, unknown>>Attribute values applied to associated rows (filter on read, values on write).
constraintsbooleanCreate foreign key constraints on sync(). Default: true.
onDeletestringON DELETE action of the foreign key constraint, e.g. 'CASCADE'.
onUpdatestringON UPDATE action of the foreign key constraint, e.g. 'CASCADE'.
hooksbooleanSequelize v6 hooks flag. With onDelete: 'CASCADE' and hooks: true, destroying an instance first loads its associated rows and destroys each of them with its own hooks (beforeDestroy, afterDestroy), then deletes the instance; without the flag PostgreSQL cascades the delete and no hooks of the target run. Only a real delete cascades this way, not the soft delete of a paranoid model.
throughstring | ModelStatic<AnyModel> | Readonly<{ model: string | ModelStatic<AnyModel>; scop…Junction model, its name, or options.
otherKeystring | Readonly<{ name?: string | undefined; field?: string | undefined; allowNull?: …Junction foreign key pointing at the target. Default: derived from the target model name.

ForeignKeyOptions ​

Foreign key given as an object instead of a plain name.

ts
const fk: ForeignKeyOptions = { name: 'authorId', field: 'author_id', allowNull: false };
User.hasMany(Post, { foreignKey: fk });
OptionTypeDescription
namestringAttribute name.
fieldstringColumn name.
allowNullbooleanWhether the key may be NULL.

ThroughOptions ​

Junction table of a belongsToMany association given as an object.

ts
const through: ThroughOptions = { model: 'ProjectTask', scope: { kind: 'member' } };
Project.belongsToMany(Task, { through });
OptionTypeDescription
modelstring | ModelStatic<AnyModel>Junction model, or the name of an implicit junction model to create.
scopeReadonly<Record<string, unknown>>Attribute values applied to junction rows.

Released under the MIT License.