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.
InitOptionsDefineOptionsAttributeOptionsReferenceOptionsUniqueOptionsValidateOptionsAttributeValidateOptionsModelNameOptionsAssociationOptionsBelongsToManyOptionsForeignKeyOptionsThroughOptions
InitOptions
Options of Model.init: table-level options plus hooks, scopes and validation. Extends DefinitionOptions.
See also: Model.init.
User.init(
{ name: DataTypes.STRING, email: DataTypes.STRING },
{
sequelize,
modelName: 'User',
paranoid: true,
defaultScope: { where: { active: true } },
scopes: { admins: { where: { role: 'admin' } } },
},
);| Option | Type | Description |
|---|---|---|
timestamps | boolean | Add createdAt / updatedAt. Default true. |
underscored | boolean | Use snake_case column names for attributes and the table name. |
freezeTableName | boolean | Use the model name as table name without pluralization. |
schema | string | PostgreSQL schema of the tables. |
paranoid | boolean | Soft-delete rows (deletedAt) instead of deleting them. |
hooks | Partial<Readonly<Record<"beforeValidate" | "afterValidate" | "validationFailed" | "befo… | Hooks added to every model. Lifecycle hooks, by hook name. |
modelName | string | Model name. Defaults to the class name. |
name | Readonly<{ 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. |
tableName | string | Table name. Defaults to the pluralized model name. |
schemaDelimiter | string | Separator between schema and table that getTableName reports (PostgreSQL always uses . in SQL). |
createdAt | string | boolean | Name of the created-at attribute, or false to disable it. Default: 'createdAt'. |
updatedAt | string | boolean | Name of the updated-at attribute, or false to disable it. Default: 'updatedAt'. |
deletedAt | string | boolean | Name of the deleted-at attribute of paranoid models. Default: 'deletedAt'. |
version | string | boolean | Optimistic locking: true adds a version attribute, a string names it. |
indexes | readonly Readonly<{ fields?: readonly IndexField[] | undefined; name?: string | undefin… | Indexes created by sync(). |
comment | string | Table comment. |
unlogged postgrelize extension | boolean | CREATE UNLOGGED TABLE on sync: faster writes, no WAL, emptied after a crash, not replicated. PostgreSQL extension. |
temporary postgrelize extension | boolean | CREATE TEMPORARY TABLE on sync: lives as long as the database session; cannot have a schema. See QueryInterface.createTable. PostgreSQL extension. |
sequelize | RuntimeOwner | Owning Sequelize instance. |
defaultScope | Readonly<Record<string, unknown>> | Scope applied to every query unless unscoped() / scope() is used. |
scopes | Readonly<Record<string, ScopeDefinition>> | Named scopes: options or functions returning options. |
whereMergeStrategy | WhereMergeStrategy | How where of merged scopes combine: 'overwrite' replaces same keys, 'and' joins them with Op.and. Default: 'overwrite'. |
validate | Readonly<Record<string, ModelValidatorFunction>> | Model-level validators; throw to fail. |
validationSchema postgrelize extension | Readonly<{ '~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.
const options: DefineOptions = { tableName: 'products', timestamps: false, paranoid: false };
const Product = sequelize.define('Product', { sku: DataTypes.STRING }, options);| Option | Type | Description |
|---|---|---|
timestamps | boolean | Add createdAt / updatedAt. Default true. |
underscored | boolean | Use snake_case column names for attributes and the table name. |
freezeTableName | boolean | Use the model name as table name without pluralization. |
schema | string | PostgreSQL schema of the tables. |
paranoid | boolean | Soft-delete rows (deletedAt) instead of deleting them. |
hooks | Partial<Readonly<Record<"beforeValidate" | "afterValidate" | "validationFailed" | "befo… | Hooks added to every model. Lifecycle hooks, by hook name. |
modelName | string | Model name. Defaults to the class name. |
name | Readonly<{ 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. |
tableName | string | Table name. Defaults to the pluralized model name. |
schemaDelimiter | string | Separator between schema and table that getTableName reports (PostgreSQL always uses . in SQL). |
createdAt | string | boolean | Name of the created-at attribute, or false to disable it. Default: 'createdAt'. |
updatedAt | string | boolean | Name of the updated-at attribute, or false to disable it. Default: 'updatedAt'. |
deletedAt | string | boolean | Name of the deleted-at attribute of paranoid models. Default: 'deletedAt'. |
version | string | boolean | Optimistic locking: true adds a version attribute, a string names it. |
indexes | readonly Readonly<{ fields?: readonly IndexField[] | undefined; name?: string | undefin… | Indexes created by sync(). |
comment | string | Table comment. |
unlogged postgrelize extension | boolean | CREATE UNLOGGED TABLE on sync: faster writes, no WAL, emptied after a crash, not replicated. PostgreSQL extension. |
temporary postgrelize extension | boolean | CREATE TEMPORARY TABLE on sync: lives as long as the database session; cannot have a schema. See QueryInterface.createTable. PostgreSQL extension. |
defaultScope | Readonly<Record<string, unknown>> | Scope applied to every query unless unscoped() / scope() is used. |
scopes | Readonly<Record<string, ScopeDefinition>> | Named scopes: options or functions returning options. |
whereMergeStrategy | WhereMergeStrategy | How where of merged scopes combine: 'overwrite' replaces same keys, 'and' joins them with Op.and. Default: 'overwrite'. |
validate | Readonly<Record<string, ModelValidatorFunction>> | Model-level validators; throw to fail. |
validationSchema postgrelize extension | Readonly<{ '~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.
const attr: AttributeOptions = {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: { isEmail: true },
};| Option | Type | Description |
|---|---|---|
type | DataTypeInput | Column type; a DataTypes entry or its factory call. |
allowNull | boolean | Whether 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). |
primaryKey | boolean | Part of the primary key. Without any primary key, an id attribute is added. Default: false. |
autoIncrement | boolean | Generated 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 extension | Readonly<{ as: unknown; stored?: boolean | undefined; }> | Generated column GENERATED ALWAYS AS (expression) STORED; never written by INSERT/UPDATE. PostgreSQL extension. |
field | string | Column name, if different from the attribute name. Default: the attribute name. |
unique | string | boolean | Readonly<{ name?: string | undefined; msg?: string | undefined; null… | Unique constraint: true, a constraint name, or { name, msg }. |
comment | string | Column comment (COMMENT ON COLUMN) written by sync(). |
values | readonly string[] | Allowed values of an ENUM column declared with the bare type, { type: DataTypes.ENUM, values: ['a', 'b'] } (Sequelize v6). Ignored for other types. |
references | string | Readonly<{ model: string | Readonly<{ tableName: string; schema?: string | und… | Foreign key reference. |
onDelete | string | ON DELETE action of the foreign key, e.g. 'CASCADE'; needs references. |
onUpdate | string | ON UPDATE action of the foreign key, e.g. 'CASCADE'; needs references. |
validate | Readonly<Record<string, unknown> & { schema?: Readonly<{ '~standard': Readonly<{ versio… | Validators run before INSERT / UPDATE. |
get | (this: M) => unknown | Custom getter, called with the model instance as this. |
set | (this: M, value: unknown) => void | Custom setter, called with the model instance as this. |
ReferenceOptions
Foreign key target of an attribute.
const ref: ReferenceOptions = { model: 'Users', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED };| Option | Type | Description |
|---|---|---|
model | string | 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). |
key | string | Referenced column. Default: primary key. |
deferrable | Readonly<{ 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.
const email: UniqueOptions = { name: 'users_email_unique', msg: 'Email already taken', nullsNotDistinct: true };| Option | Type | Description |
|---|---|---|
name | string | Constraint name; attributes with the same name form a composite unique key. |
msg | string | Validation message used when the constraint is violated. |
nullsNotDistinct postgrelize extension | boolean | UNIQUE 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.
const opts: ValidateOptions = { skip: ['password'], hooks: false };
await user.validate(opts);| Option | Type | Description |
|---|---|---|
hooks | boolean | Run beforeValidate / afterValidate / validationFailed hooks. Default: true. |
skip | readonly string[] | Attributes to skip. |
fields | readonly 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).
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');
},
};| Option | Type | Description |
|---|---|---|
schema | Readonly<{ '~standard': Readonly<{ version: 1; vendor: string; validate: (value: unknow… | Standard Schema the value must satisfy. |
notNull | boolean | Readonly<{ args?: unknown; msg?: string | undefined; }> | Custom message for allowNull: false violations. |
ModelNameOptions
Singular and plural forms of a model name (Sequelize v6 ModelNameOptions).
const name: ModelNameOptions = { singular: 'person', plural: 'people' };| Option | Type | Description |
|---|---|---|
singular | string | Singular model name. |
plural | string | Plural model name. |
AssociationOptions
Options shared by all association methods (Sequelize v6 AssociationOptions). Used by hasOne, hasMany, belongsTo and (extended) belongsToMany.
See also: Model.hasMany.
const opts: AssociationOptions = {
as: 'posts',
foreignKey: { name: 'authorId', allowNull: false },
onDelete: 'CASCADE',
};
User.hasMany(Post, opts);| Option | Type | Description |
|---|---|---|
as | string | Readonly<{ singular: string; plural: string; }> | Alias: string, or { singular, plural } for multi associations. Default: the target model name. |
foreignKey | string | Readonly<{ name?: string | undefined; field?: string | undefined; allowNull?: … | Foreign key attribute name or options. |
sourceKey | string | Attribute of the source referenced by the foreign key (hasOne / hasMany / belongsToMany). |
targetKey | string | Attribute of the target referenced by the foreign key (belongsTo / belongsToMany). |
scope | Readonly<Record<string, unknown>> | Attribute values applied to associated rows (filter on read, values on write). |
constraints | boolean | Create foreign key constraints on sync(). Default: true. |
onDelete | string | ON DELETE action of the foreign key constraint, e.g. 'CASCADE'. |
onUpdate | string | ON UPDATE action of the foreign key constraint, e.g. 'CASCADE'. |
hooks | boolean | Sequelize 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.
const opts: BelongsToManyOptions = { through: 'ProjectTask', foreignKey: 'projectId', otherKey: 'taskId' };
Project.belongsToMany(Task, opts);| Option | Type | Description |
|---|---|---|
as | string | Readonly<{ singular: string; plural: string; }> | Alias: string, or { singular, plural } for multi associations. Default: the target model name. |
foreignKey | string | Readonly<{ name?: string | undefined; field?: string | undefined; allowNull?: … | Foreign key attribute name or options. |
sourceKey | string | Attribute of the source referenced by the foreign key (hasOne / hasMany / belongsToMany). |
targetKey | string | Attribute of the target referenced by the foreign key (belongsTo / belongsToMany). |
scope | Readonly<Record<string, unknown>> | Attribute values applied to associated rows (filter on read, values on write). |
constraints | boolean | Create foreign key constraints on sync(). Default: true. |
onDelete | string | ON DELETE action of the foreign key constraint, e.g. 'CASCADE'. |
onUpdate | string | ON UPDATE action of the foreign key constraint, e.g. 'CASCADE'. |
hooks | boolean | Sequelize 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. |
through | string | ModelStatic<AnyModel> | Readonly<{ model: string | ModelStatic<AnyModel>; scop… | Junction model, its name, or options. |
otherKey | string | 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.
const fk: ForeignKeyOptions = { name: 'authorId', field: 'author_id', allowNull: false };
User.hasMany(Post, { foreignKey: fk });| Option | Type | Description |
|---|---|---|
name | string | Attribute name. |
field | string | Column name. |
allowNull | boolean | Whether the key may be NULL. |
ThroughOptions
Junction table of a belongsToMany association given as an object.
const through: ThroughOptions = { model: 'ProjectTask', scope: { kind: 'member' } };
Project.belongsToMany(Task, { through });| Option | Type | Description |
|---|---|---|
model | string | ModelStatic<AnyModel> | Junction model, or the name of an implicit junction model to create. |
scope | Readonly<Record<string, unknown>> | Attribute values applied to junction rows. |