Skip to content

postgrelize / Model

Class: Model<TAttributes, TCreationAttributes> ​

Defined in: src/model/model.ts:30

Base class of models, API-compatible with Sequelize v6 Model.

Example ​

ts
class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  declare id: CreationOptional<number>;
  declare email: string;
}
User.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: DataTypes.STRING }, { sequelize });

Extends ​

  • ModelInstanceValues<TAttributes>
  • ModelInstancePersistence<TAttributes>
  • ModelStatics

Type Parameters ​

TAttributes ​

TAttributes extends object = any

Attribute types (usually InferAttributes<M>).

TCreationAttributes ​

TCreationAttributes extends object = TAttributes

Attribute types accepted on creation (usually InferCreationAttributes<M>).

Constructors ​

Constructor ​

new Model<TAttributes, TCreationAttributes>(values?, options?): Model<TAttributes, TCreationAttributes>

Defined in: src/model/model.ts:84

Builds an instance without saving it. Prefer Model.build.

Parameters ​

values? ​

Values | Partial<TCreationAttributes> = {}

Attribute values.

options? ​

BuildOptions = {}

Build options.

Returns ​

Model<TAttributes, TCreationAttributes>

Inherited from ​

ModelInstanceValues<TAttributes>.constructor

Properties ​

_attributes ​

_attributes: TAttributes

Defined in: src/model/model.ts:59

Phantom type of attributes; not set at runtime.


_creationAttributes ​

_creationAttributes: TCreationAttributes

Defined in: src/model/model.ts:62

Phantom type of creation attributes; not set at runtime.


_previousDataValues ​

_previousDataValues: Partial<TAttributes>

Defined in: src/model/model.ts:68

Values as of the last load/save.


dataValues ​

dataValues: TAttributes

Defined in: src/model/model.ts:65

Current attribute values.

Inherited from ​

ModelInstanceValues.dataValues


isNewRecord ​

isNewRecord: boolean

Defined in: src/model/model.ts:71

True until the instance is saved or when built from a query result.


afterBulkCreate ​

static afterBulkCreate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:65

Adds a afterBulkCreate hook: Model.afterBulkCreate(fn) or Model.afterBulkCreate(name, fn).


afterBulkDestroy ​

static afterBulkDestroy: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:77

Adds a afterBulkDestroy hook: Model.afterBulkDestroy(fn) or Model.afterBulkDestroy(name, fn).


afterBulkRestore ​

static afterBulkRestore: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:83

Adds a afterBulkRestore hook: Model.afterBulkRestore(fn) or Model.afterBulkRestore(name, fn).


afterBulkUpdate ​

static afterBulkUpdate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:71

Adds a afterBulkUpdate hook: Model.afterBulkUpdate(fn) or Model.afterBulkUpdate(name, fn).


afterCreate ​

static afterCreate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:29

Adds a afterCreate hook: Model.afterCreate(fn) or Model.afterCreate(name, fn).


afterDestroy ​

static afterDestroy: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:47

Adds a afterDestroy hook: Model.afterDestroy(fn) or Model.afterDestroy(name, fn).


afterFind ​

static afterFind: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:95

Adds a afterFind hook: Model.afterFind(fn) or Model.afterFind(name, fn).


afterRestore ​

static afterRestore: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:53

Adds a afterRestore hook: Model.afterRestore(fn) or Model.afterRestore(name, fn).


afterSave ​

static afterSave: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:41

Adds a afterSave hook: Model.afterSave(fn) or Model.afterSave(name, fn).


afterSync ​

static afterSync: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:101

Adds an afterSync hook: runs after Model.sync() and after this model's turn in sequelize.sync().


afterUpdate ​

static afterUpdate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:35

Adds a afterUpdate hook: Model.afterUpdate(fn) or Model.afterUpdate(name, fn).


afterUpsert ​

static afterUpsert: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:59

Adds a afterUpsert hook: Model.afterUpsert(fn) or Model.afterUpsert(name, fn).


afterValidate ​

static afterValidate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:20

Adds a afterValidate hook: Model.afterValidate(fn) or Model.afterValidate(name, fn).


beforeBulkCreate ​

static beforeBulkCreate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:62

Adds a beforeBulkCreate hook: Model.beforeBulkCreate(fn) or Model.beforeBulkCreate(name, fn).


beforeBulkDestroy ​

static beforeBulkDestroy: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:74

Adds a beforeBulkDestroy hook: Model.beforeBulkDestroy(fn) or Model.beforeBulkDestroy(name, fn).


beforeBulkRestore ​

static beforeBulkRestore: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:80

Adds a beforeBulkRestore hook: Model.beforeBulkRestore(fn) or Model.beforeBulkRestore(name, fn).


beforeBulkUpdate ​

static beforeBulkUpdate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:68

Adds a beforeBulkUpdate hook: Model.beforeBulkUpdate(fn) or Model.beforeBulkUpdate(name, fn).


beforeCount ​

static beforeCount: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:104

Adds a beforeCount hook: Model.beforeCount(fn) or Model.beforeCount(name, fn).


beforeCreate ​

static beforeCreate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:26

Adds a beforeCreate hook: Model.beforeCreate(fn) or Model.beforeCreate(name, fn).


beforeDestroy ​

static beforeDestroy: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:44

Adds a beforeDestroy hook: Model.beforeDestroy(fn) or Model.beforeDestroy(name, fn).


beforeFind ​

static beforeFind: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:86

Adds a beforeFind hook: Model.beforeFind(fn) or Model.beforeFind(name, fn).


beforeFindAfterExpandIncludeAll ​

static beforeFindAfterExpandIncludeAll: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:89

Adds a beforeFindAfterExpandIncludeAll hook: Model.beforeFindAfterExpandIncludeAll(fn) or Model.beforeFindAfterExpandIncludeAll(name, fn).


beforeFindAfterOptions ​

static beforeFindAfterOptions: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:92

Adds a beforeFindAfterOptions hook: Model.beforeFindAfterOptions(fn) or Model.beforeFindAfterOptions(name, fn).


beforeRestore ​

static beforeRestore: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:50

Adds a beforeRestore hook: Model.beforeRestore(fn) or Model.beforeRestore(name, fn).


beforeSave ​

static beforeSave: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:38

Adds a beforeSave hook: Model.beforeSave(fn) or Model.beforeSave(name, fn).


beforeSync ​

static beforeSync: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:98

Adds a beforeSync hook: runs before Model.sync() and before this model's turn in sequelize.sync().


beforeUpdate ​

static beforeUpdate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:32

Adds a beforeUpdate hook: Model.beforeUpdate(fn) or Model.beforeUpdate(name, fn).


beforeUpsert ​

static beforeUpsert: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:56

Adds a beforeUpsert hook: Model.beforeUpsert(fn) or Model.beforeUpsert(name, fn).


beforeValidate ​

static beforeValidate: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:17

Adds a beforeValidate hook: Model.beforeValidate(fn) or Model.beforeValidate(name, fn).


validationFailed ​

static validationFailed: NamedHookAdder

Defined in: src/model/mixins/model-hooks.ts:23

Adds a validationFailed hook: Model.validationFailed(fn) or Model.validationFailed(name, fn).

Accessors ​

_model ​

Get Signature ​

get _model(): typeof Model

Defined in: src/model/model.ts:74

Model class of the instance.

Returns ​

typeof Model


oldValues ​

Get Signature ​

get oldValues(): Readonly<Record<string, unknown>> | null | undefined

Defined in: src/model/model-base.ts:50

postgrelize extension

For instances returned with returningOld: true: attribute values of the row before the statement, or null when the row did not exist (inserted). undefined otherwise. PostgreSQL 18+.

Returns ​

Readonly<Record<string, unknown>> | null | undefined


sequelize ​

Get Signature ​

get sequelize(): Sequelize

Defined in: src/model/model-base.ts:55

Sequelize instance the model belongs to.

Returns ​

Sequelize


wasInserted ​

Get Signature ​

get wasInserted(): boolean | undefined

Defined in: src/model/model-base.ts:41

postgrelize extension

For instances returned by insert, create / bulkCreate / upsert with onConflict: true when the row was inserted, false when an existing row was updated (or nothing was written). undefined otherwise. PostgreSQL extension.

Returns ​

boolean | undefined


associations ​

Get Signature ​

get static associations(): Readonly<Record<string, Association>>

Defined in: src/model/mixins/model-associations.ts:20

Associations of the model by alias (Sequelize v6 Model.associations).

Returns ​

Readonly<Record<string, Association>>


modelName ​

Get Signature ​

get static modelName(): string

Defined in: src/model/model-base.ts:60

Name the model was registered under, as given by modelName in the init options (default: the class name).

Returns ​

string


options ​

Get Signature ​

get static options(): DefinitionOptions

Defined in: src/model/model-base.ts:86

Model options after defaults were applied.

Returns ​

DefinitionOptions


primaryKeyAttribute ​

Get Signature ​

get static primaryKeyAttribute(): string

Defined in: src/model/model-base.ts:75

First primary key attribute name.

Returns ​

string


primaryKeyAttributes ​

Get Signature ​

get static primaryKeyAttributes(): readonly string[]

Defined in: src/model/model-base.ts:81

All primary key attribute names.

Returns ​

readonly string[]


queryInterface ​

Get Signature ​

get static queryInterface(): QueryInterface

Defined in: src/model/mixins/model-schema.ts:77

Schema API of the owning Sequelize instance (Sequelize v6 Model.queryInterface).

Returns ​

QueryInterface


rawAttributes ​

Get Signature ​

get static rawAttributes(): Readonly<Record<string, AttributeDefinition>>

Defined in: src/model/model-base.ts:70

Normalized attributes keyed by attribute name.

Returns ​

Readonly<Record<string, AttributeDefinition>>


sequelize ​

Get Signature ​

get static sequelize(): Sequelize

Defined in: src/model/model-base.ts:91

Sequelize instance the model belongs to.

Returns ​

Sequelize


tableName ​

Get Signature ​

get static tableName(): string

Defined in: src/model/model-base.ts:65

Name of the database table backing the model (pluralized model name unless tableName was set).

Returns ​

string

Methods ​

changed() ​

Call Signature ​

changed(): false | (keyof TAttributes & string)[]

Defined in: src/model/model-instance-values.ts:142

Lists the attributes changed since the instance was loaded or last saved.

Returns ​

false | (keyof TAttributes & string)[]

Changed attribute names, or false when nothing changed.

Example ​
ts
user.set('email', 'ada@example.com');
const changedFields = user.changed();
Inherited from ​

ModelInstanceValues.changed

Call Signature ​

changed(key): boolean

Defined in: src/model/model-instance-values.ts:150

Checks whether one attribute changed since the instance was loaded or last saved.

Parameters ​
key ​

keyof TAttributes & string

Attribute name.

Returns ​

boolean

True when changed.

Inherited from ​

ModelInstanceValues.changed

Call Signature ​

changed(key, value): void

Defined in: src/model/model-instance-values.ts:158

Marks an attribute as changed or unchanged, which controls whether Model.save writes it.

Parameters ​
key ​

keyof TAttributes & string

Attribute name.

value ​

boolean

Changed flag.

Returns ​

void

Inherited from ​

ModelInstanceValues.changed

Call Signature ​

changed<K>(key): boolean

Defined in: src/model/model-instance-values.ts:166

Checks whether one attribute changed, addressed by a key of the model class (Sequelize v6 signature, so keyof M works in generic code).

Type Parameters ​
K ​

K extends keyof Model<TAttributes, TCreationAttributes>

Parameters ​
key ​

K

Attribute name.

Returns ​

boolean

True when changed.

Inherited from ​

ModelInstanceValues.changed

Call Signature ​

changed<K>(key, value): void

Defined in: src/model/model-instance-values.ts:174

Marks an attribute as changed or unchanged, addressed by a key of the model class (Sequelize v6 signature).

Type Parameters ​
K ​

K extends keyof Model<TAttributes, TCreationAttributes>

Parameters ​
key ​

K

Attribute name.

value ​

boolean

Changed flag.

Returns ​

void

Inherited from ​

ModelInstanceValues.changed


decrement() ​

decrement(fields, options?): Promise<Model<TAttributes, TCreationAttributes>>

Defined in: src/model/model-instance-persistence.ts:242

Decrements numeric attributes of this row in the database (SET x = x - by). The instance values are not reloaded; call Model.reload to read the new numbers.

Parameters ​

fields ​

AttributeAmounts<TAttributes>

Attribute name(s) or map of amounts.

options? ​

Omit<IncrementOptions<TAttributes>, "where"> = {}

by (default 1), silent, and query options.

Returns ​

Promise<Model<TAttributes, TCreationAttributes>>

This instance.

Example ​

ts
await user.decrement('credits', { by: 5 });

Inherited from ​

ModelInstancePersistence.decrement


destroy() ​

destroy(options?): Promise<void>

Defined in: src/model/model-instance-persistence.ts:168

Deletes the row of this instance. For paranoid models it sets deletedAt instead, unless force: true. Runs beforeDestroy/afterDestroy hooks unless hooks: false.

Parameters ​

options? ​

InstanceDestroyOptions = {}

Destroy options (force, hooks, query options).

Returns ​

Promise<void>

Resolves when deleted.

Example ​

ts
await user.destroy();

Inherited from ​

ModelInstancePersistence.destroy


equals() ​

equals(other): boolean

Defined in: src/model/model-instance-values.ts:222

Compares the primary keys of two instances.

Parameters ​

other ​

Model

Instance to compare with.

Returns ​

boolean

True when all primary key values are equal.

Example ​

ts
const other = User.build({ id: user.get('id') });
const same = user.equals(other);

Inherited from ​

ModelInstanceValues.equals


equalsOneOf() ​

equalsOneOf(others): boolean

Defined in: src/model/model-instance-values.ts:236

Tells whether the instance equals any of the given instances (same model and primary keys).

Parameters ​

others ​

readonly Model<any, any>[]

Instances to compare with.

Returns ​

boolean

True when at least one equals this instance.

Example ​

ts
const known = user.equalsOneOf(users);

Inherited from ​

ModelInstanceValues.equalsOneOf


get() ​

Call Signature ​

get(options?): TAttributes

Defined in: src/model/model-instance-values.ts:26

Returns all attribute values of the instance; no query is run.

Parameters ​
options? ​

Readonly<{ clone?: boolean; plain?: boolean; raw?: boolean; }>

plain: true returns a copy of all values with custom getters applied; raw: true skips custom getters.

Returns ​

TAttributes

Values object.

Example ​
ts
const values = user.get({ plain: true });
Inherited from ​

ModelInstanceValues.get

Call Signature ​

get<K>(key, options?): Model<TAttributes, TCreationAttributes>[K]

Defined in: src/model/model-instance-values.ts:39

Returns one attribute value, applying its custom getter unless raw is set.

Type Parameters ​
K ​

K extends keyof Model<TAttributes, TCreationAttributes>

Parameters ​
key ​

K

Attribute name.

options? ​

Readonly<{ clone?: boolean; plain?: boolean; raw?: boolean; }>

raw: true skips the custom getter.

Returns ​

Model<TAttributes, TCreationAttributes>[K]

Attribute value.

Example ​
ts
const email = user.get('email');
Inherited from ​

ModelInstanceValues.get

Call Signature ​

get(key, options?): unknown

Defined in: src/model/model-instance-values.ts:53

Returns the value of an attribute or association that is addressed by a plain string, for example an included association or a dynamic key.

Parameters ​
key ​

string

Attribute or association name.

options? ​

Readonly<{ clone?: boolean; plain?: boolean; raw?: boolean; }>

raw: true skips the custom getter.

Returns ​

unknown

The value, untyped.

Example ​
ts
const posts = user.get('Posts');
Inherited from ​

ModelInstanceValues.get


getDataValue() ​

getDataValue<K>(key): TAttributes[K]

Defined in: src/model/model-instance-values.ts:112

Reads the stored value of an attribute, bypassing its custom getter.

Type Parameters ​

K ​

K extends string | number | symbol

Parameters ​

key ​

K

Attribute name.

Returns ​

TAttributes[K]

Raw value.

Example ​

ts
const stored = user.getDataValue('email');

Inherited from ​

ModelInstanceValues.getDataValue


increment() ​

increment(fields, options?): Promise<Model<TAttributes, TCreationAttributes>>

Defined in: src/model/model-instance-persistence.ts:217

Increments numeric attributes of this row in the database (SET x = x + by). The instance values are not reloaded; call Model.reload to read the new numbers.

Parameters ​

fields ​

AttributeAmounts<TAttributes>

Attribute name(s) or map of amounts.

options? ​

Omit<IncrementOptions<TAttributes>, "where"> = {}

by (default 1), silent, and query options.

Returns ​

Promise<Model<TAttributes, TCreationAttributes>>

This instance.

Example ​

ts
await user.increment('loginCount');
await user.increment({ loginCount: 2, score: 10 });

Inherited from ​

ModelInstancePersistence.increment


isSoftDeleted() ​

isSoftDeleted(): boolean

Defined in: src/model/model-instance-persistence.ts:200

Whether this instance of a paranoid model is soft-deleted.

Returns ​

boolean

True when deletedAt is set.

Throws ​

Error when the model is not paranoid.

Example ​

ts
if (user.isSoftDeleted()) {
  await user.restore();
}

Inherited from ​

ModelInstancePersistence.isSoftDeleted


previous() ​

Call Signature ​

previous(): Partial<TAttributes>

Defined in: src/model/model-instance-values.ts:189

Returns the previous values of all changed attributes.

Returns ​

Partial<TAttributes>

Previous values keyed by attribute name.

Example ​
ts
user.set('email', 'ada@example.com');
const before = user.previous();
Inherited from ​

ModelInstanceValues.previous

Call Signature ​

previous<K>(key): TAttributes[K] | undefined

Defined in: src/model/model-instance-values.ts:201

Returns the value an attribute had before it was changed.

Type Parameters ​
K ​

K extends string | number | symbol

Parameters ​
key ​

K

Attribute name.

Returns ​

TAttributes[K] | undefined

Previous value.

Example ​
ts
user.set('email', 'ada@example.com');
const before = user.previous('email');
Inherited from ​

ModelInstanceValues.previous


reload() ​

reload(options?): Promise<Model<TAttributes, TCreationAttributes>>

Defined in: src/model/model-instance-persistence.ts:150

Re-reads the row from the database and replaces the instance values, discarding unsaved changes. The row is read with findOne by primary key, so include, attributes, paranoid, lock, scopes and the find hooks apply as in Sequelize v6 (a soft-deleted row needs paranoid: false).

Parameters ​

options? ​

FindOptions<TAttributes> = {}

Find options; where is always the primary key of this instance.

Returns ​

Promise<Model<TAttributes, TCreationAttributes>>

This instance.

Throws ​

InstanceError when the row no longer exists.

Example ​

ts
await user.reload({ transaction });
await user.reload({ include: [Post], lock: transaction.LOCK.UPDATE });

Inherited from ​

ModelInstancePersistence.reload


restore() ​

restore(options?): Promise<void>

Defined in: src/model/model-instance-persistence.ts:184

Clears deletedAt of this soft-deleted instance of a paranoid model.

Parameters ​

options? ​

QueryOptionsBase & Readonly<{ hooks?: boolean; }> = {}

Query options; hooks: false skips restore hooks.

Returns ​

Promise<void>

Resolves when restored.

Throws ​

Error when the model is not paranoid.

Example ​

ts
await user.restore();

Inherited from ​

ModelInstancePersistence.restore


save() ​

save(options?): Promise<Model<TAttributes, TCreationAttributes>>

Defined in: src/model/model-instance-persistence.ts:42

Inserts the instance when it is new, otherwise updates its changed attributes. Runs validation and the beforeValidate/afterValidate, beforeSave/afterSave and beforeCreate/beforeUpdate (and after*) hooks unless disabled in the options; updating an unchanged instance sends no query.

Parameters ​

options? ​

SaveOptions<TAttributes> = {}

Save options.

Returns ​

Promise<Model<TAttributes, TCreationAttributes>>

This instance with values returned by the database.

Throws ​

ValidationError when validation fails.

Throws ​

UniqueConstraintError when a unique constraint is violated.

Throws ​

ForeignKeyConstraintError when a foreign key constraint is violated.

Example ​

ts
const user = User.build({ email: 'ada@example.com' });
await user.save({ transaction });

Inherited from ​

ModelInstancePersistence.save


set() ​

Call Signature ​

set<K>(key, value, options?): this

Defined in: src/model/model-instance-values.ts:75

Sets one attribute value, applying its custom setter unless raw is set. Nothing is written to the database until Model.save; the attribute is marked as changed when the value differs.

Type Parameters ​
K ​

K extends string | number | symbol

Parameters ​
key ​

K

Attribute name.

value ​

TAttributes[K]

New value.

options? ​

Readonly<{ raw?: boolean; }>

raw: true skips the custom setter and change tracking.

Returns ​

this

This instance.

Example ​
ts
user.set('email', 'ada@example.com');
await user.save();
Inherited from ​

ModelInstanceValues.set

Call Signature ​

set(values, options?): this

Defined in: src/model/model-instance-values.ts:92

Sets several attribute values at once, applying custom setters unless raw is set.

Parameters ​
values ​

Values | Partial<TAttributes>

Attribute values.

options? ​

Readonly<{ raw?: boolean; }>

raw: true skips custom setters and change tracking.

Returns ​

this

This instance.

Example ​
ts
user.set({ email: 'ada@example.com', active: true });
Inherited from ​

ModelInstanceValues.set


setAttributes() ​

setAttributes(updates): this

Defined in: src/model/model-instance-values.ts:250

Alias of Model.set for several values (Sequelize v6 setAttributes).

Parameters ​

updates ​

Values | Partial<TAttributes>

Attribute values.

Returns ​

this

This instance.

Example ​

ts
user.setAttributes({ email: 'ada@example.com' });

Inherited from ​

ModelInstanceValues.setAttributes


setDataValue() ​

setDataValue<K>(key, value): this

Defined in: src/model/model-instance-values.ts:127

Writes the stored value of an attribute, bypassing its custom setter, and marks it as changed.

Type Parameters ​

K ​

K extends string | number | symbol

Parameters ​

key ​

K

Attribute name.

value ​

TAttributes[K]

New value.

Returns ​

this

This instance.

Example ​

ts
user.setDataValue('email', 'ada@example.com');

Inherited from ​

ModelInstanceValues.setDataValue


toJSON() ​

toJSON(): TAttributes

Defined in: src/model/model-instance-values.ts:290

Returns a deep copy of the values with custom getters applied, used by JSON.stringify.

Returns ​

TAttributes

Plain object.

Example ​

ts
const json = JSON.stringify(user);

Inherited from ​

ModelInstanceValues.toJSON


toString() ​

toString(): string

Defined in: src/model/model-instance-values.ts:277

Describes the instance as [object SequelizeInstance:Model].

Returns ​

string

The description.

Example ​

ts
String(user); // '[object SequelizeInstance:User]'

Inherited from ​

ModelInstanceValues.toString


update() ​

Call Signature ​

update<K>(key, value, options?): Promise<Model<TAttributes, TCreationAttributes>>

Defined in: src/model/model-instance-persistence.ts:80

Sets one attribute and saves the instance.

Type Parameters ​
K ​

K extends string | number | symbol

Parameters ​
key ​

K

Attribute name.

value ​

Literal | Fn | Col | TAttributes[K]

New value, or a fn / col / literal expression.

options? ​

SaveOptions<TAttributes>

Save options.

Returns ​

Promise<Model<TAttributes, TCreationAttributes>>

This instance.

Throws ​

ValidationError when validation fails.

Example ​
ts
await user.update('email', 'ada@example.com');
Inherited from ​

ModelInstancePersistence.update

Call Signature ​

update(values, options?): Promise<Model<TAttributes, TCreationAttributes>>

Defined in: src/model/model-instance-persistence.ts:97

Sets values and saves the instance, same as Model.set followed by Model.save.

Parameters ​
values ​

UpdateValues<TAttributes>

New values.

options? ​

SaveOptions<TAttributes>

Save options.

Returns ​

Promise<Model<TAttributes, TCreationAttributes>>

This instance.

Throws ​

ValidationError when validation fails.

Example ​
ts
await user.update({ email: 'ada@example.com' });
Inherited from ​

ModelInstancePersistence.update


validate() ​

validate(options?): Promise<void>

Defined in: src/model/model-instance-persistence.ts:60

Runs the attribute validators and model validators without saving (Sequelize v6 instance.validate()).

Parameters ​

options? ​

ValidateOptions = {}

hooks, skip, fields.

Returns ​

Promise<void>

Resolves when valid.

Throws ​

ValidationError with all failures.

Example ​

ts
await user.validate();

Inherited from ​

ModelInstancePersistence.validate


where() ​

where(checkVersion?): Record<string, unknown> | undefined

Defined in: src/model/model-instance-values.ts:264

Condition that selects this row: its primary key values keyed by column name.

Parameters ​

checkVersion? ​

boolean

Also match the optimistic-locking version value.

Returns ​

Record<string, unknown> | undefined

The where object (the model's whereCollection option when it has no primary key).

Example ​

ts
const where = user.where();

Inherited from ​

ModelInstanceValues.where


addHook() ​

static addHook<MS>(this, type, nameOrFn, fn?): MS

Defined in: src/model/mixins/model-hooks.ts:123

Registers a hook function for a lifecycle event of this model, same as the named adders such as Model.beforeCreate(fn). Hooks of one type run in registration order.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

Parameters ​

this ​

MS

The model class.

type ​

"beforeValidate" | "afterValidate" | "validationFailed" | "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDestroy" | "afterDestroy" | "beforeRestore" | "afterRestore" | "beforeUpsert" | "afterUpsert" | "beforeBulkCreate" | "afterBulkCreate" | "beforeBulkUpdate" | "afterBulkUpdate" | "beforeBulkDestroy" | "afterBulkDestroy" | "beforeBulkRestore" | "afterBulkRestore" | "beforeFind" | "beforeFindAfterExpandIncludeAll" | "beforeFindAfterOptions" | "afterFind" | "beforeCount" | "beforeConnect" | "afterConnect" | "beforeDisconnect" | "afterDisconnect" | "beforePoolAcquire" | "afterPoolAcquire" | "beforeQuery" | "afterQuery" | "beforeSync" | "afterSync" | "beforeBulkSync" | "afterBulkSync" | "beforeDefine" | "afterDefine" | "beforeInit" | "afterInit" | "beforeAssociate" | "afterAssociate"

Hook type, e.g. 'beforeCreate'.

nameOrFn ​

string | HookFunction

Hook name (to remove it later) or the hook function.

fn? ​

HookFunction

Hook function when a name is given.

Returns ​

MS

The model class.

Example ​

ts
User.addHook('beforeCreate', 'normalizeEmail', async (instance: User) => {
  instance.set('email', String(instance.get('email')).toLowerCase());
});

See ​

Hooks guide


addScope() ​

static addScope(name, scope, options?): void

Defined in: src/model/mixins/model-scopes.ts:70

Adds a named scope (or replaces the default scope with name 'defaultScope').

Parameters ​

name ​

string

Scope name.

scope ​

ScopeDefinition

Options or a function returning options.

options? ​

Readonly<{ override?: boolean; }> = {}

override: true replaces an existing scope.

Returns ​

void

Throws ​

Error when the scope exists and override is not set.

Example ​

ts
User.addScope('active', { where: { active: true } });
User.addScope('olderThan', (age: number) => ({ where: { age: { [Op.gt]: age } } }));

aggregate() ​

static aggregate<M, T>(this, field, aggregateFunction, options?): Promise<T>

Defined in: src/model/mixins/model-aggregates.ts:29

Runs one SQL aggregate function over a column (SELECT fn(col) ...), applying the default scope and the paranoid filter. The function name is checked against a safe name pattern, never concatenated unchecked.

Type Parameters ​

M ​

M extends AnyModel

T ​

T = unknown

Parameters ​

this ​

ModelStatic<M>

The model class.

field ​

"*" | keyof Attributes<M>

Attribute name or '*'.

aggregateFunction ​

string

SQL aggregate function name, e.g. 'max'.

options? ​

AggregateOptions<Attributes<M>> = {}

Options (where, distinct, group, plain: false to get rows, query options).

Returns ​

Promise<T>

Aggregated value: a number for count and numeric attributes, otherwise parsed like the attribute; rows with plain: false.

Example ​

ts
const avgPrice = await Product.aggregate('price', 'avg', { where: { active: true } });

belongsTo() ​

static belongsTo<M, T>(this, target, options?): BelongsTo<M, T>

Defined in: src/model/mixins/model-associations.ts:94

Declares that each row of this model refers to one row of the target; the foreign key column lives on this model's table. Adds accessors such as getX / setX / createX to instances.

Type Parameters ​

M ​

M extends AnyModel

T ​

T extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The source model class.

target ​

ModelStatic<T>

Associated model.

options? ​

Readonly<{ as?: string | Readonly<{ plural: string; singular: string; }>; constraints?: boolean; foreignKey?: string | Readonly<{ allowNull?: boolean; field?: string; name?: string; }>; hooks?: boolean; onDelete?: string; onUpdate?: string; scope?: Readonly<Record<string, unknown>>; sourceKey?: string; targetKey?: string; }>

Association options.

Returns ​

BelongsTo<M, T>

The association.

Example ​

ts
Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' });

See ​

Associations guide


belongsToMany() ​

static belongsToMany<M, T>(this, target, options): BelongsToMany<M, T>

Defined in: src/model/mixins/model-associations.ts:156

Declares a many-to-many relation between this model and the target through a junction table.

Type Parameters ​

M ​

M extends AnyModel

T ​

T extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The source model class.

target ​

ModelStatic<T>

Associated model.

options ​

BelongsToManyOptions

Association options with through.

Returns ​

BelongsToMany<M, T>

The association.

Example ​

ts
Project.belongsToMany(Task, { through: 'ProjectTasks' });

build() ​

static build<M>(this, values?, options?): M

Defined in: src/model/mixins/model-writers.ts:50

Builds a new instance in memory without touching the database; call save() to insert it. Defaults and custom setters are applied.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

values? ​

Values | CreationAttributes<M>

Attribute values.

options? ​

Readonly<{ include?: IncludeOption; isNewRecord?: boolean; raw?: boolean; }>

Build options.

Returns ​

M

New instance.

Example ​

ts
const user = User.build({ email: 'ada@example.com' });
await user.save();

bulkBuild() ​

static bulkBuild<M>(this, records, options?): M[]

Defined in: src/model/mixins/model-writers.ts:70

Builds several new instances in memory, same as calling Model.build for each record.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

records ​

readonly (Values | CreationAttributes<M>)[]

Attribute values per instance.

options? ​

Readonly<{ include?: IncludeOption; isNewRecord?: boolean; raw?: boolean; }>

Build options.

Returns ​

M[]

New instances.

Example ​

ts
const tags = Tag.bulkBuild([{ name: 'news' }, { name: 'sports' }]);

bulkCreate() ​

static bulkCreate<M>(this, records, options?): Promise<M[]>

Defined in: src/model/mixins/model-writers.ts:122

Inserts many rows with one multi-row INSERT ... RETURNING. Runs beforeBulkCreate and afterBulkCreate hooks; rows are not validated unless validate: true. ignoreDuplicates, updateOnDuplicate and onConflict map to ON CONFLICT; individualHooks or include insert row by row like Sequelize v6.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

records ​

readonly CreationAttributes<M>[]

Attribute values per row.

options? ​

BulkCreateOptions<Attributes<M>> = {}

Bulk create options.

Returns ​

Promise<M[]>

Instances with values returned by the database.

Throws ​

ValidationError with validate: true when a row is invalid.

Throws ​

UniqueConstraintError when a unique constraint is violated and no conflict handling is set.

Example ​

ts
const tags = await Tag.bulkCreate([{ name: 'news' }, { name: 'sports' }], { ignoreDuplicates: true });

See ​

Model.insert for the PostgreSQL variant that returns only the rows actually written.


copyFrom() ​

static copyFrom<M>(this, rows, options?): Promise<number>

Defined in: src/model/mixins/model-postgres.ts:252

postgrelize extension

Bulk-loads rows with COPY ... FROM STDIN (text format) — much faster than INSERT for large volumes. No hooks or validation run; missing values are written as NULL. createdAt / updatedAt are filled when the model has timestamps. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

rows ​

Iterable<CreationAttributes<M>, any, any> | AsyncIterable<CreationAttributes<M>, any, any>

Rows (array, iterable or async iterable of attribute values).

options? ​

CopyFromOptions<Attributes<M>> = {}

columns (attribute names; default: keys of the first row of an array) and query options.

Returns ​

Promise<number>

Number of copied rows.

Example ​

ts
const copied = await Task.copyFrom(
  [{ title: 'first' }, { title: 'second' }],
  { columns: ['title'] },
);

copyTo() ​

static copyTo<M>(this, options?): AsyncGenerator<Buffer<ArrayBufferLike>, void, undefined>

Defined in: src/model/mixins/model-postgres.ts:281

postgrelize extension

Streams COPY (SELECT ...) TO STDOUT output — the fastest way to export rows (e.g. CSV). Default scope, paranoid filter, with / source and includes apply. Values of the query are inlined as escaped literals because COPY cannot take parameters (ADR-013). Stopping early drains the rest before the connection is released. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

options? ​

CopyToOptions<Attributes<M>> = {}

Find options and output format (format, header, ...).

Returns ​

AsyncGenerator<Buffer<ArrayBufferLike>, void, undefined>

Async iterator of raw output chunks.

Example ​

ts
for await (const chunk of User.copyTo({ attributes: ['id', 'email'], format: 'csv', header: true })) {
  process.stdout.write(chunk);
}

count() ​

Call Signature ​

static count<M>(this, options): Promise<GroupedCountResultItem[]>

Defined in: src/model/mixins/model-finders.ts:142

Counts rows per group, applying the default scope and the paranoid filter. Runs beforeCount hooks unless hooks: false.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options ​

CountWithOptions<Attributes<M>>

Count options with group.

Returns ​

Promise<GroupedCountResultItem[]>

One { count, ...groupColumns } item per group.

Example ​
ts
const rows = await User.count({ group: ['role'] });
rows.map((r) => r.count);

Call Signature ​

static count<M>(this, options?): Promise<number>

Defined in: src/model/mixins/model-finders.ts:159

Counts rows, applying the default scope and the paranoid filter. Runs beforeCount hooks unless hooks: false.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options? ​

Omit<CountOptions<Attributes<M>>, "group">

Count options (where, col, distinct, include).

Returns ​

Promise<number>

The count. Use the group overload for per-group counts.

Example ​
ts
const active = await User.count({ where: { active: true } });

create() ​

static create<M>(this, values?, options?): Promise<M>

Defined in: src/model/mixins/model-writers.ts:96

Builds an instance and inserts it with INSERT ... RETURNING, running validation and the create/save hooks. With onConflict (PostgreSQL extension) the insert may be skipped or turned into an update, and instance.wasInserted tells which happened.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

values? ​

CreationAttributes<M>

Attribute values.

options? ​

CreateOptions<Attributes<M>> = {}

Create options (fields, hooks, validate, include, onConflict, query options).

Returns ​

Promise<M>

Saved instance.

Throws ​

ValidationError when validation fails.

Throws ​

UniqueConstraintError when a unique constraint is violated.

Throws ​

ForeignKeyConstraintError when a foreign key constraint is violated.

Throws ​

DatabaseError for other database errors.

Example ​

ts
const user = await User.create({ email: 'ada@example.com' }, { transaction });

decrement() ​

static decrement<M>(this, fields, options?): Promise<[affectedRows: M[], affectedCount: number]>

Defined in: src/model/mixins/model-writers.ts:299

Atomically decrements numeric attributes of the rows matching where (SET x = x - by).

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

fields ​

AttributeAmounts<Attributes<M>>

Attribute name(s), or a map of attribute to amount.

options? ​

IncrementOptions<Attributes<M>> = {}

Decrement options (where, by default 1, silent, query options).

Returns ​

Promise<[affectedRows: M[], affectedCount: number]>

[affectedRows, affectedCount]: the updated instances and their number.

Example ​

ts
await Product.decrement({ stock: 3 }, { where: { id: 7 } });

Inherited from ​

ModelInstancePersistence.decrement


deleteStatement() ​

static deleteStatement<M>(this, options?): WriteStatement

Defined in: src/model/mixins/model-postgres.ts:178

postgrelize extension

Builds a DELETE for a data-modifying CTE (with). It is a real delete, also for paranoid models, and ignores the paranoid filter. With returning: true the deleted rows can be read through source, e.g. to move them to another table. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

options? ​

WriteStatementOptions<Attributes<M>> = {}

where, returning.

Returns ​

WriteStatement

Statement for the with option.

Example ​

ts
const done = Task.deleteStatement({ where: { done: true }, returning: true });
const removed = await Task.findAll({ with: { done }, source: 'done' });

describe() ​

static describe(schema?, options?): Promise<Record<string, Readonly<{ allowNull: boolean; comment: string | null; defaultValue: unknown; primaryKey: boolean; special: readonly string[]; type: string; }>>>

Defined in: src/model/mixins/model-schema.ts:92

Describes the table of this model: its columns, types, nullability and defaults.

Parameters ​

schema? ​

string

Schema to read; defaults to the model's schema, then current_schema().

options? ​

QueryOptionsBase = {}

Query options.

Returns ​

Promise<Record<string, Readonly<{ allowNull: boolean; comment: string | null; defaultValue: unknown; primaryKey: boolean; special: readonly string[]; type: string; }>>>

Column descriptions by column name.

Example ​

ts
const columns = await User.describe();

destroy() ​

Call Signature ​

static destroy<M>(this, options): Promise<M[]>

Defined in: src/model/mixins/model-writers.ts:218

Deletes rows matching where and returns the deleted instances (DELETE ... RETURNING, a PostgreSQL extension). For paranoid models the rows are soft-deleted unless force: true.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class.

options ​

QueryOptionsBase & object & BulkHookOptions & Readonly<{ returning: true; }>

Destroy options with returning: true.

Returns ​

Promise<M[]>

Deleted instances.

Example ​
ts
const removed = await Post.destroy({ where: { published: false }, returning: true });
Inherited from ​

ModelInstancePersistence.destroy

Call Signature ​

static destroy<M>(this, options?): Promise<number>

Defined in: src/model/mixins/model-writers.ts:232

Deletes rows matching where (truncate: true empties the table instead). For paranoid models the rows are soft-deleted (deletedAt is set) unless force: true. Runs bulk destroy hooks unless hooks: false.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class.

options? ​

DestroyOptions<Attributes<M>>

Destroy options.

Returns ​

Promise<number>

Number of deleted rows.

Inherited from ​

ModelInstancePersistence.destroy


drop() ​

static drop(options?): Promise<void>

Defined in: src/model/mixins/model-schema.ts:55

Drops the table of this model and the enum types it owns.

Parameters ​

options? ​

DropOptions = {}

cascade, schema and query options.

Returns ​

Promise<void>

Resolves when done.

Example ​

ts
await Task.drop({ cascade: true });

dropSchema() ​

static dropSchema(schema): Promise<void>

Defined in: src/model/mixins/model-schema.ts:114

Drops a schema with DROP SCHEMA (shortcut of queryInterface.dropSchema, Sequelize v6 Model.dropSchema).

Parameters ​

schema ​

string

Schema name.

Returns ​

Promise<void>

Resolves when done.

Example ​

ts
await User.dropSchema('tenant_1');

findAll() ​

static findAll<M>(this, options?): Promise<M[]>

Defined in: src/model/mixins/model-finders.ts:43

Selects all rows matching the options, applying the default scope and, for paranoid models, hiding soft-deleted rows. Runs beforeFind and afterFind hooks unless hooks: false.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options? ​

FindOptions<Attributes<M>> = {}

Query options (where, attributes, order, limit, include, ...).

Returns ​

Promise<M[]>

Instances, or plain objects with raw: true.

Example ​

ts
const posts = await Post.findAll({
  where: { published: true },
  order: [['createdAt', 'DESC']],
  limit: 20,
  include: [User],
});

See ​

Model.findEach to stream large result sets.


findAndCountAll() ​

Call Signature ​

static findAndCountAll<M>(this, options?): Promise<FindAndCountResult<M>>

Defined in: src/model/mixins/model-finders.ts:182

Runs Model.findAll and Model.count with the same filter, so limit / offset paginate the rows while count is the total.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options? ​

Omit<FindAndCountOptions<Attributes<M>>, "group">

Query options.

Returns ​

Promise<FindAndCountResult<M>>

Total count and the current page of rows.

Example ​
ts
const { count, rows } = await Post.findAndCountAll({ where: { published: true }, limit: 10, offset: 20 });

Call Signature ​

static findAndCountAll<M>(this, options): Promise<FindAndCountResult<M, GroupedCountResultItem[]>>

Defined in: src/model/mixins/model-finders.ts:199

With group, count is an array with one item per group (the grouped attributes and the row count of the group) instead of a number.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options ​

Omit<FindAndCountOptions<Attributes<M>>, "group"> & Required<Pick<FindAndCountOptions<Attributes<M>>, "group">>

Query options including group.

Returns ​

Promise<FindAndCountResult<M, GroupedCountResultItem[]>>

Per-group counts and the current page of rows.

Example ​
ts
const { count, rows } = await Post.findAndCountAll({ group: ['status'] });

findByPk() ​

Call Signature ​

static findByPk<M>(this, key, options): Promise<M>

Defined in: src/model/mixins/model-finders.ts:98

Selects the row with the given primary key and rejects when none is found.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

key ​

unknown

Primary key value.

options ​

Omit<NonNullFindOptions<Attributes<M>>, "where">

Query options other than where, with rejectOnEmpty.

Returns ​

Promise<M>

Instance.

Throws ​

EmptyResultError (or the given error) when nothing is found.

Example ​
ts
const user = await User.findByPk(42, { rejectOnEmpty: true });

Call Signature ​

static findByPk<M>(this, key?, options?): Promise<M | null>

Defined in: src/model/mixins/model-finders.ts:116

Selects the row with the given primary key.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

key? ​

unknown

Primary key value.

options? ​

Omit<FindOptions<Attributes<M>>, "where">

Query options other than where.

Returns ​

Promise<M | null>

Instance or null.

Example ​
ts
const user = await User.findByPk(42, { include: [Profile] });

findCreateFind() ​

static findCreateFind<M>(this, options): Promise<[M, boolean]>

Defined in: src/model/mixins/model-finders.ts:246

Finds a row; when none matches, inserts it and, if that fails with a unique violation (a concurrent insert won), reads the row again. Unlike findOrCreate the insert is not wrapped in a transaction, so it suits code that already handles the race itself. Inside a transaction the insert uses a savepoint, which fixes v6 returning an unsaved instance after a conflict.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options ​

FindOrCreateOptions<Attributes<M>>

where to search (required; its equality values also seed the new row), defaults to add on creation.

Returns ​

Promise<[M, boolean]>

[instance, created].

Throws ​

Error when where is missing.

Example ​

ts
const [tag, created] = await Tag.findCreateFind({ where: { name: 'news' }, defaults: { color: 'red' } });

findEach() ​

static findEach<M>(this, options?, cursor?): AsyncGenerator<M, void, undefined>

Defined in: src/model/mixins/model-postgres.ts:226

postgrelize extension

Streams rows with a server-side cursor (DECLARE ... CURSOR + FETCH n), so large result sets are not loaded at once. Runs inside options.transaction or its own transaction; the cursor is closed when iteration ends or is stopped early. Joined includes are not supported. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

options? ​

FindOptions<Attributes<M>> = {}

Find options.

cursor? ​

Readonly<{ batchSize?: number; }> = {}

batchSize (rows per FETCH, default 100).

Returns ​

AsyncGenerator<M, void, undefined>

Async iterator of instances.

Example ​

ts
for await (const user of User.findEach({ where: { active: true } }, { batchSize: 500 })) {
  console.log(user.get('email'));
}

findOne() ​

Call Signature ​

static findOne<M>(this, options): Promise<M>

Defined in: src/model/mixins/model-finders.ts:62

Selects the first row matching the options and rejects when none is found.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options ​

NonNullFindOptions<Attributes<M>>

Query options with rejectOnEmpty.

Returns ​

Promise<M>

Instance.

Throws ​

EmptyResultError (or the given error) when nothing is found.

Example ​
ts
const user = await User.findOne({ where: { email: 'ada@example.com' }, rejectOnEmpty: true });

Call Signature ​

static findOne<M>(this, options?): Promise<M | null>

Defined in: src/model/mixins/model-finders.ts:74

Selects the first row matching the options (LIMIT 1 unless limit is given).

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options? ​

FindOptions<Attributes<M>>

Query options.

Returns ​

Promise<M | null>

Instance or null.


findOrBuild() ​

static findOrBuild<M>(this, options): Promise<[M, boolean]>

Defined in: src/model/mixins/model-finders.ts:267

Finds a row, or builds a new unsaved instance when none matches; nothing is inserted.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options ​

FindOrCreateOptions<Attributes<M>>

where to search (its equality values also seed the built instance), defaults to add when building.

Returns ​

Promise<[M, boolean]>

[instance, built].

Example ​

ts
const [tag, built] = await Tag.findOrBuild({ where: { name: 'news' } });
if (built) {
  await tag.save();
}

findOrCreate() ​

static findOrCreate<M>(this, options): Promise<[M, boolean]>

Defined in: src/model/mixins/model-finders.ts:224

Finds a row, or creates it when none matches. Creation runs inside a transaction (a nested one when options.transaction is given); when creation fails but the row exists after all (a concurrent insert won), that row is returned, otherwise the error is rethrown.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class (or a scoped model class from Model.scope).

options ​

FindOrCreateOptions<Attributes<M>>

where to search (its equality values also seed the new row), defaults to add on creation.

Returns ​

Promise<[M, boolean]>

[instance, created].

Example ​

ts
const [tag, created] = await Tag.findOrCreate({ where: { name: 'news' }, defaults: { color: 'red' } });

getAssociationForAlias() ​

static getAssociationForAlias(target, alias?): Association<AnyModel, AnyModel> | null

Defined in: src/model/mixins/model-associations.ts:53

Association to target for an alias, or the one declared without alias when alias is not a string.

Parameters ​

target ​

Target model.

name ​

string

alias? ​

string | { plural?: string; } | null

Association alias.

Returns ​

Association<AnyModel, AnyModel> | null

The association, or null.

Example ​

ts
const association = User.getAssociationForAlias(Post, 'posts');

getAssociations() ​

static getAssociations(target): Association<AnyModel, AnyModel>[]

Defined in: src/model/mixins/model-associations.ts:36

Associations of this model whose target is the given model.

Parameters ​

target ​

Target model.

name ​

string

Returns ​

Association<AnyModel, AnyModel>[]

Matching associations.

Example ​

ts
const toPosts = User.getAssociations(Post);

getAttributes() ​

static getAttributes(): Readonly<Record<string, AttributeDefinition>>

Defined in: src/model/model-base.ts:136

Returns the normalized attribute definitions, same as Model.rawAttributes.

Returns ​

Readonly<Record<string, AttributeDefinition>>

Attribute definitions.

Example ​

ts
const attributes = User.getAttributes();
Object.keys(attributes);

getTableName() ​

static getTableName(): string | Readonly<{ delimiter: string; name: string; schema: string; table: string; tableName: string; toString: () => string; }>

Defined in: src/model/model-base.ts:150

Table name, or the qualified table ({ tableName, schema, delimiter, ... }, like v6) when the model has a schema. String(qualified) is the quoted "schema"."table" reference.

Returns ​

string | Readonly<{ delimiter: string; name: string; schema: string; table: string; tableName: string; toString: () => string; }>

Table name or qualified table.

Example ​

ts
const table = User.getTableName();

hasAlias() ​

static hasAlias(alias): boolean

Defined in: src/model/mixins/model-associations.ts:76

Tells whether an association with this alias exists.

Parameters ​

alias ​

string

Association alias.

Returns ​

boolean

True when the model has the association.

Example ​

ts
if (User.hasAlias('posts')) {}

hasHook() ​

static hasHook(type): boolean

Defined in: src/model/mixins/model-hooks.ts:165

Checks whether hooks of the type are registered on the model.

Parameters ​

type ​

"beforeValidate" | "afterValidate" | "validationFailed" | "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDestroy" | "afterDestroy" | "beforeRestore" | "afterRestore" | "beforeUpsert" | "afterUpsert" | "beforeBulkCreate" | "afterBulkCreate" | "beforeBulkUpdate" | "afterBulkUpdate" | "beforeBulkDestroy" | "afterBulkDestroy" | "beforeBulkRestore" | "afterBulkRestore" | "beforeFind" | "beforeFindAfterExpandIncludeAll" | "beforeFindAfterOptions" | "afterFind" | "beforeCount" | "beforeConnect" | "afterConnect" | "beforeDisconnect" | "afterDisconnect" | "beforePoolAcquire" | "afterPoolAcquire" | "beforeQuery" | "afterQuery" | "beforeSync" | "afterSync" | "beforeBulkSync" | "afterBulkSync" | "beforeDefine" | "afterDefine" | "beforeInit" | "afterInit" | "beforeAssociate" | "afterAssociate"

Hook type.

Returns ​

boolean

True when at least one hook exists, false after all were removed and undefined (typed boolean, like Sequelize v6) for a type that never had a hook.

Example ​

ts
const registered = User.hasHook('beforeCreate');

hasHooks() ​

static hasHooks(type): boolean

Defined in: src/model/mixins/model-hooks.ts:179

Alias of Model.hasHook.

Parameters ​

type ​

"beforeValidate" | "afterValidate" | "validationFailed" | "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDestroy" | "afterDestroy" | "beforeRestore" | "afterRestore" | "beforeUpsert" | "afterUpsert" | "beforeBulkCreate" | "afterBulkCreate" | "beforeBulkUpdate" | "afterBulkUpdate" | "beforeBulkDestroy" | "afterBulkDestroy" | "beforeBulkRestore" | "afterBulkRestore" | "beforeFind" | "beforeFindAfterExpandIncludeAll" | "beforeFindAfterOptions" | "afterFind" | "beforeCount" | "beforeConnect" | "afterConnect" | "beforeDisconnect" | "afterDisconnect" | "beforePoolAcquire" | "afterPoolAcquire" | "beforeQuery" | "afterQuery" | "beforeSync" | "afterSync" | "beforeBulkSync" | "afterBulkSync" | "beforeDefine" | "afterDefine" | "beforeInit" | "afterInit" | "beforeAssociate" | "afterAssociate"

Hook type.

Returns ​

boolean

Same as Model.hasHook.

Example ​

ts
const registered = User.hasHooks('afterFind');

hasMany() ​

static hasMany<M, T>(this, target, options?): HasMany<M, T>

Defined in: src/model/mixins/model-associations.ts:136

Declares that each row of this model has many related target rows; the foreign key column lives on the target's table.

Type Parameters ​

M ​

M extends AnyModel

T ​

T extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The source model class.

target ​

ModelStatic<T>

Associated model.

options? ​

Readonly<{ as?: string | Readonly<{ plural: string; singular: string; }>; constraints?: boolean; foreignKey?: string | Readonly<{ allowNull?: boolean; field?: string; name?: string; }>; hooks?: boolean; onDelete?: string; onUpdate?: string; scope?: Readonly<Record<string, unknown>>; sourceKey?: string; targetKey?: string; }>

Association options.

Returns ​

HasMany<M, T>

The association.

Example ​

ts
User.hasMany(Post, { foreignKey: 'authorId', as: 'posts' });

hasOne() ​

static hasOne<M, T>(this, target, options?): HasOne<M, T>

Defined in: src/model/mixins/model-associations.ts:115

Declares that each row of this model has at most one related target row; the foreign key column lives on the target's table.

Type Parameters ​

M ​

M extends AnyModel

T ​

T extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The source model class.

target ​

ModelStatic<T>

Associated model.

options? ​

Readonly<{ as?: string | Readonly<{ plural: string; singular: string; }>; constraints?: boolean; foreignKey?: string | Readonly<{ allowNull?: boolean; field?: string; name?: string; }>; hooks?: boolean; onDelete?: string; onUpdate?: string; scope?: Readonly<Record<string, unknown>>; sourceKey?: string; targetKey?: string; }>

Association options.

Returns ​

HasOne<M, T>

The association.

Example ​

ts
User.hasOne(Profile, { foreignKey: 'userId' });

increment() ​

static increment<M>(this, fields, options?): Promise<[affectedRows: M[], affectedCount: number]>

Defined in: src/model/mixins/model-writers.ts:274

Atomically increments numeric attributes of the rows matching where (SET x = x + by).

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

fields ​

AttributeAmounts<Attributes<M>>

Attribute name(s), or a map of attribute to amount.

options? ​

IncrementOptions<Attributes<M>> = {}

Increment options (where, by default 1, silent, query options).

Returns ​

Promise<[affectedRows: M[], affectedCount: number]>

[affectedRows, affectedCount]: the updated instances and their number.

Example ​

ts
await Post.increment('views', { by: 1, where: { id: 5 } });

Inherited from ​

ModelInstancePersistence.increment


init() ​

static init<MS, M>(this, attributes, options): MS

Defined in: src/model/model-base.ts:117

Defines attributes and options of the model and registers it in sequelize.models. Does not touch the database; call Model.sync or run migrations to create the table.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

M ​

M extends AnyModel = InstanceType<MS>

Parameters ​

this ​

MS

The model class being initialized.

attributes ​

ModelAttributes<M>

Attribute definitions.

options ​

InitOptions

Model options, including the sequelize instance.

Returns ​

MS

The model class.

Example ​

ts
class Project extends Model {}
Project.init(
  { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING },
  { sequelize, modelName: 'Project', paranoid: true },
);

insert() ​

static insert<M>(this, values, options?): Promise<M[]>

Defined in: src/model/mixins/model-postgres.ts:52

postgrelize extension

Inserts rows with INSERT ... ON CONFLICT and returns the inserted or updated rows. Unlike bulkCreate, rows skipped by DO NOTHING or by the DO UPDATE ... WHERE condition are not returned. Each instance has wasInserted. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

values ​

CreationAttributes<M> | readonly CreationAttributes<M>[]

Attribute values of one row or several rows.

options? ​

InsertOptions<Attributes<M>> = {}

Insert options (onConflict, fields, hooks, validate, overriding, returningOld, query options).

Returns ​

Promise<M[]>

Instances of the rows written by the statement.

See ​

Example ​

ts
const items = [{ sku: 'a-1', qty: 5 }];
const rows = await Product.insert(items, {
  onConflict: { target: ['sku'], action: { update: { qty: literal('"Product"."qty" + EXCLUDED."qty"') } } },
});
const inserted = rows.filter((row) => row.wasInserted);

insertFrom() ​

static insertFrom<M>(this, source, options): Promise<M[]>

Defined in: src/model/mixins/model-postgres.ts:77

postgrelize extension

INSERT INTO ... SELECT: inserts the rows produced by a subquery. Returns the inserted (or, with onConflict, updated) rows with wasInserted. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The target model class.

source ​

Subquery

Subquery from Model.subquery(); its columns must match options.columns.

options ​

InsertFromOptions<Attributes<M>>

Target columns, onConflict and query options.

Returns ​

Promise<M[]>

Written rows.

Example ​

ts
await Task.insertFrom(
  Post.subquery({ attributes: ['id', 'title'], where: { published: false } }),
  { columns: ['postId', 'title'] },
);

insertStatement() ​

static insertStatement<M>(this, rows, options?): WriteStatement

Defined in: src/model/mixins/model-postgres.ts:201

postgrelize extension

Builds an INSERT of attribute-keyed rows for a data-modifying CTE (with). Defaults and timestamps are filled in; no hooks or validation run. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

rows ​

readonly CreationAttributes<M>[]

Rows to insert (at least one).

options? ​

Pick<WriteStatementOptions<Attributes<M>>, "returning"> = {}

returning.

Returns ​

WriteStatement

Statement for the with option.

Throws ​

Error without rows.

Example ​

ts
const added = Task.insertStatement([{ title: 'write docs' }], { returning: true });
const rows = await Task.findAll({ with: { added }, source: 'added' });

max() ​

static max<T, M>(this, field, options?): Promise<T>

Defined in: src/model/mixins/model-aggregates.ts:55

Finds the largest value of an attribute with max().

Type Parameters ​

T ​

T = unknown

M ​

M extends AnyModel = AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

field ​

keyof Attributes<M>

Attribute name.

options? ​

AggregateOptions<Attributes<M>>

Options, see Model.aggregate.

Returns ​

Promise<T>

Maximum or null when there are no rows.

Example ​

ts
const highest = await Product.max('price');

merge() ​

static merge<M>(this, options): Promise<Readonly<{ rowCount: number; rows: readonly Readonly<{ action: MergeActionName; instance: M; }>[]; }>>

Defined in: src/model/mixins/model-postgres.ts:104

postgrelize extension

MERGE INTO ... USING ... (PostgreSQL 15+). With returning: true (PostgreSQL 17+) returns the written rows with the action taken. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

options ​

MergeOptions<Attributes<M>> & QueryOptionsBase & Readonly<{ returning?: boolean; returningOld?: boolean; }>

Source, join condition and WHEN clauses.

Returns ​

Promise<Readonly<{ rowCount: number; rows: readonly Readonly<{ action: MergeActionName; instance: M; }>[]; }>>

Affected row count and, with returning, { action, instance } per row.

Throws ​

DatabaseError when the server rejects the statement (for example on PostgreSQL older than 15).

Example ​

ts
await Product.merge({
  source: [{ sku: 'a', qty: 5 }],
  on: { sku: col('source.sku') },
  whenMatched: { update: { qty: literal('"Product"."qty" + "source"."qty"') } },
  whenNotMatched: { insert: true },
});

min() ​

static min<T, M>(this, field, options?): Promise<T>

Defined in: src/model/mixins/model-aggregates.ts:80

Finds the smallest value of an attribute with min().

Type Parameters ​

T ​

T = unknown

M ​

M extends AnyModel = AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

field ​

keyof Attributes<M>

Attribute name.

options? ​

AggregateOptions<Attributes<M>>

Options, see Model.aggregate.

Returns ​

Promise<T>

Minimum or null when there are no rows.

Example ​

ts
const lowest = await Product.min('price', { where: { active: true } });

refreshAttributes() ​

static refreshAttributes(): void

Defined in: src/model/mixins/model-schema.ts:139

Rebuilds the normalized attribute definitions from the model's init input.

Returns ​

void

Example ​

ts
User.refreshAttributes();

removeAttribute() ​

static removeAttribute(attribute): void

Defined in: src/model/mixins/model-schema.ts:127

Removes an attribute from the model definition, e.g. a column added by an association.

Parameters ​

attribute ​

string

Attribute name.

Returns ​

void

Example ​

ts
User.removeAttribute('legacyFlag');

removeHook() ​

static removeHook<MS>(this, type, nameOrFn?): MS

Defined in: src/model/mixins/model-hooks.ts:145

Removes hooks of a type from this model: one by name or function, or all of them.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

Parameters ​

this ​

MS

The model class.

type ​

"beforeValidate" | "afterValidate" | "validationFailed" | "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDestroy" | "afterDestroy" | "beforeRestore" | "afterRestore" | "beforeUpsert" | "afterUpsert" | "beforeBulkCreate" | "afterBulkCreate" | "beforeBulkUpdate" | "afterBulkUpdate" | "beforeBulkDestroy" | "afterBulkDestroy" | "beforeBulkRestore" | "afterBulkRestore" | "beforeFind" | "beforeFindAfterExpandIncludeAll" | "beforeFindAfterOptions" | "afterFind" | "beforeCount" | "beforeConnect" | "afterConnect" | "beforeDisconnect" | "afterDisconnect" | "beforePoolAcquire" | "afterPoolAcquire" | "beforeQuery" | "afterQuery" | "beforeSync" | "afterSync" | "beforeBulkSync" | "afterBulkSync" | "beforeDefine" | "afterDefine" | "beforeInit" | "afterInit" | "beforeAssociate" | "afterAssociate"

Hook type.

nameOrFn? ​

string | HookFunction

Hook name or function; all hooks of the type when omitted.

Returns ​

MS

The model class.

Example ​

ts
User.removeHook('beforeCreate', 'normalizeEmail');

restore() ​

static restore<M>(this, options?): Promise<void>

Defined in: src/model/mixins/model-writers.ts:255

Restores soft-deleted rows of a paranoid model by setting deletedAt back to NULL.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

options? ​

RestoreOptions<Attributes<M>> = {}

Rows to restore and hook options.

Returns ​

Promise<void>

Resolves when done.

Throws ​

Error when the model is not paranoid.

Example ​

ts
await Post.restore({ where: { userId: 1 } });

Inherited from ​

ModelInstancePersistence.restore


runHooks() ​

static runHooks(type, ...args): Promise<void>

Defined in: src/model/mixins/model-hooks.ts:194

Runs the hooks of a type with the given arguments (model hooks, then Sequelize-level hooks).

Parameters ​

type ​

"beforeValidate" | "afterValidate" | "validationFailed" | "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDestroy" | "afterDestroy" | "beforeRestore" | "afterRestore" | "beforeUpsert" | "afterUpsert" | "beforeBulkCreate" | "afterBulkCreate" | "beforeBulkUpdate" | "afterBulkUpdate" | "beforeBulkDestroy" | "afterBulkDestroy" | "beforeBulkRestore" | "afterBulkRestore" | "beforeFind" | "beforeFindAfterExpandIncludeAll" | "beforeFindAfterOptions" | "afterFind" | "beforeCount" | "beforeConnect" | "afterConnect" | "beforeDisconnect" | "afterDisconnect" | "beforePoolAcquire" | "afterPoolAcquire" | "beforeQuery" | "afterQuery" | "beforeSync" | "afterSync" | "beforeBulkSync" | "afterBulkSync" | "beforeDefine" | "afterDefine" | "beforeInit" | "afterInit" | "beforeAssociate" | "afterAssociate"

Hook type.

args ​

...readonly unknown[]

Hook arguments.

Returns ​

Promise<void>

Resolves when all hooks finished.

Example ​

ts
await User.runHooks('beforeCreate', user, {});

schema() ​

static schema<MS>(this, schema, options?): MS

Defined in: src/model/mixins/model-schema-binding.ts:33

Returns a model class whose queries target a PostgreSQL schema, like Sequelize v6.

The copy has the attributes, hooks, scopes and associations of this model as they are at the time of the call and keeps the scope selection of this class. Changes made to the original afterwards are not seen by the copy.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

Parameters ​

this ​

MS

The model class being bound.

schema ​

string

Schema name.

options? ​

string | Readonly<{ schemaDelimiter?: string; }>

Separator between schema and table reported by getTableName (a string, or { schemaDelimiter }); PostgreSQL always qualifies with . in SQL. Defaults to ..

Returns ​

MS

Schema-bound model class (instances are instances of this model).

Example ​

ts
const TenantUser = User.schema('tenant_a');
await TenantUser.findAll(); // SELECT ... FROM "tenant_a"."users"
TenantUser.getTableName(); // { tableName: 'users', schema: 'tenant_a', delimiter: '.' }

scope() ​

static scope<MS>(this, ...selectors): MS

Defined in: src/model/mixins/model-scopes.ts:29

Creates a model class that applies the given scopes to its queries instead of the default scope. The original class is not changed.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

Parameters ​

this ​

MS

The model class.

selectors ​

...readonly (ScopeSelector | readonly ScopeSelector[])[]

Scope names, { method: [name, ...args] }, inline options, 'defaultScope', or null.

Returns ​

MS

Scoped model class (instances are instances of this model).

Throws ​

Error when a named scope does not exist.

Example ​

ts
await User.scope('active', { method: ['olderThan', 18] }).findAll();

See ​

Querying guide


subquery() ​

static subquery<M>(this, options?): Subquery

Defined in: src/model/mixins/model-postgres.ts:132

postgrelize extension

Builds a SELECT that can be embedded in another query: in where ([Op.in], =, exists()), in attributes (scalar subquery) and as a source of insertFrom / merge. Default scope and paranoid filter apply; values stay bound parameters of the outer statement. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class the subquery selects from.

options? ​

QueryOptionsBase & Omit<SelectOptions, "where"> & object & Readonly<{ from?: Readonly<Record<string, FromSourceOption>>; source?: string | Subquery; with?: Readonly<Record<string, Subquery | WriteStatement | Readonly<{ cycle?: Readonly<...>; materialized?: boolean; query: Subquery | WriteStatement; recursive?: Subquery; search?: Readonly<...>; unionAll?: boolean; }>>>; }> & Readonly<{ as?: string; }> = {}

Find options (attributes, where, order, limit, include, ...) and as (table alias).

Returns ​

Subquery

Subquery expression.

Example ​

ts
await User.findAll({ where: { id: { [Op.in]: Post.subquery({ attributes: ['userId'], where: { published: true } }) } } });

sum() ​

static sum<M>(this, field, options?): Promise<number>

Defined in: src/model/mixins/model-aggregates.ts:105

Adds up the values of an attribute with sum().

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

field ​

keyof Attributes<M>

Attribute name.

options? ​

AggregateOptions<Attributes<M>>

Options, see Model.aggregate.

Returns ​

Promise<number>

Sum, or null when there are no rows (as returned by PostgreSQL).

Example ​

ts
const total = await Invoice.sum('amount', { where: { paid: true } });

sync() ​

static sync<MS>(this, options?): Promise<MS>

Defined in: src/model/mixins/model-schema.ts:34

Creates the table of this model and its indexes when missing. force: true drops it first (with CASCADE); alter changes an existing table to match the model.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

Parameters ​

this ​

MS

The model class.

options? ​

SyncOptions = {}

force, alter, match, schema and query options.

Returns ​

Promise<MS>

The model class.

Example ​

ts
await User.sync({ alter: true });

See ​

Schema guide


truncate() ​

static truncate(options?): Promise<void>

Defined in: src/model/mixins/model-schema.ts:70

Removes all rows with TRUNCATE, without running hooks.

Parameters ​

options? ​

QueryOptionsBase & Readonly<{ cascade?: boolean; restartIdentity?: boolean; }> = {}

cascade, restartIdentity and query options.

Returns ​

Promise<void>

Resolves when done.

Example ​

ts
await Task.truncate({ restartIdentity: true, cascade: true });

unscoped() ​

static unscoped<MS>(this): MS

Defined in: src/model/mixins/model-scopes.ts:53

Creates a model class that applies no scope at all, not even the default scope.

Type Parameters ​

MS ​

MS extends ModelStatic<AnyModel>

Parameters ​

this ​

MS

The model class.

Returns ​

MS

Unscoped model class.

Example ​

ts
const everyone = await User.unscoped().findAll();

update() ​

Call Signature ​

static update<M>(this, values, options): Promise<[affectedCount: number, affectedRows: M[]]>

Defined in: src/model/mixins/model-writers.ts:172

Updates all rows matching where with one UPDATE and refreshes updatedAt unless silent. Values are validated unless validate: false; bulk hooks run unless hooks: false. With returning: true the updated instances are returned as the second element.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class.

values ​

UpdateValues<Attributes<M>>

New attribute values.

options ​

Omit<UpdateOptions<Attributes<M>>, "returning"> & object

Update options with returning: true; where is required.

Returns ​

Promise<[affectedCount: number, affectedRows: M[]]>

[affectedCount, affectedRows].

Throws ​

ValidationError when the new values are invalid.

Example ​
ts
const [count, rows] = await Post.update({ published: true }, { where: { userId: 1 }, returning: true });
Inherited from ​

ModelInstancePersistence.update

Call Signature ​

static update<M>(this, values, options): Promise<[affectedCount: number]>

Defined in: src/model/mixins/model-writers.ts:192

Updates all rows matching where with one UPDATE and refreshes updatedAt unless silent. Values are validated unless validate: false; bulk hooks run unless hooks: false.

Type Parameters ​
M ​

M extends AnyModel

Parameters ​
this ​

ModelStatic<M>

The model class.

values ​

UpdateValues<Attributes<M>>

New attribute values.

options ​

UpdateOptions<Attributes<M>>

Update options; where is required.

Returns ​

Promise<[affectedCount: number]>

[affectedCount].

Throws ​

ValidationError when the new values are invalid.

Example ​
ts
const [count] = await Post.update({ published: true }, { where: { userId: 1 } });
Inherited from ​

ModelInstancePersistence.update


updateStatement() ​

static updateStatement<M>(this, values, options?): WriteStatement

Defined in: src/model/mixins/model-postgres.ts:155

postgrelize extension

Builds an UPDATE for a data-modifying CTE (with); nothing runs until the outer query does. No hooks or validation run; updatedAt is set unless silent. With returning: true the CTE can be read through source. Queries with such a CTE always use the writer. PostgreSQL extension.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

values ​

UpdateValues<Attributes<M>>

New attribute values.

options? ​

UpdateStatementOptions<Attributes<M>> = {}

where, returning, silent.

Returns ​

WriteStatement

Statement for the with option.

Example ​

ts
const bumped = Task.updateStatement({ done: true }, { where: { id: 1 }, returning: true });
const rows = await Task.findAll({ with: { bumped }, source: 'bumped' });

upsert() ​

static upsert<M>(this, values, options?): Promise<[M, boolean | null]>

Defined in: src/model/mixins/model-writers.ts:149

Inserts a row, or updates it when it conflicts with a unique key (INSERT ... ON CONFLICT DO UPDATE, Sequelize v6 upsert). Runs the beforeUpsert and afterUpsert hooks.

Type Parameters ​

M ​

M extends AnyModel

Parameters ​

this ​

ModelStatic<M>

The model class.

values ​

CreationAttributes<M>

Attribute values.

options? ​

UpsertOptions<Attributes<M>> = {}

Upsert options (conflictFields, fields, onConflict, query options).

Returns ​

Promise<[M, boolean | null]>

[instance, null] like Sequelize v6, or [instance, created] with onConflict.

Throws ​

ValidationError when validation fails.

Throws ​

UniqueConstraintError when a unique constraint other than the conflict target is violated.

Example ​

ts
const [user] = await User.upsert({ email: 'ada@example.com', name: 'Ada' }, { conflictFields: ['email'] });

Released under the MIT License.