postgrelize / Model
Class: Model<TAttributes, TCreationAttributes> ​
Defined in: src/model/model.ts:30
Base class of models, API-compatible with Sequelize v6 Model.
Example ​
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 ​
staticafterBulkCreate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:65
Adds a afterBulkCreate hook: Model.afterBulkCreate(fn) or Model.afterBulkCreate(name, fn).
afterBulkDestroy ​
staticafterBulkDestroy:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:77
Adds a afterBulkDestroy hook: Model.afterBulkDestroy(fn) or Model.afterBulkDestroy(name, fn).
afterBulkRestore ​
staticafterBulkRestore:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:83
Adds a afterBulkRestore hook: Model.afterBulkRestore(fn) or Model.afterBulkRestore(name, fn).
afterBulkUpdate ​
staticafterBulkUpdate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:71
Adds a afterBulkUpdate hook: Model.afterBulkUpdate(fn) or Model.afterBulkUpdate(name, fn).
afterCreate ​
staticafterCreate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:29
Adds a afterCreate hook: Model.afterCreate(fn) or Model.afterCreate(name, fn).
afterDestroy ​
staticafterDestroy:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:47
Adds a afterDestroy hook: Model.afterDestroy(fn) or Model.afterDestroy(name, fn).
afterFind ​
staticafterFind:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:95
Adds a afterFind hook: Model.afterFind(fn) or Model.afterFind(name, fn).
afterRestore ​
staticafterRestore:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:53
Adds a afterRestore hook: Model.afterRestore(fn) or Model.afterRestore(name, fn).
afterSave ​
staticafterSave:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:41
Adds a afterSave hook: Model.afterSave(fn) or Model.afterSave(name, fn).
afterSync ​
staticafterSync: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 ​
staticafterUpdate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:35
Adds a afterUpdate hook: Model.afterUpdate(fn) or Model.afterUpdate(name, fn).
afterUpsert ​
staticafterUpsert:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:59
Adds a afterUpsert hook: Model.afterUpsert(fn) or Model.afterUpsert(name, fn).
afterValidate ​
staticafterValidate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:20
Adds a afterValidate hook: Model.afterValidate(fn) or Model.afterValidate(name, fn).
beforeBulkCreate ​
staticbeforeBulkCreate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:62
Adds a beforeBulkCreate hook: Model.beforeBulkCreate(fn) or Model.beforeBulkCreate(name, fn).
beforeBulkDestroy ​
staticbeforeBulkDestroy:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:74
Adds a beforeBulkDestroy hook: Model.beforeBulkDestroy(fn) or Model.beforeBulkDestroy(name, fn).
beforeBulkRestore ​
staticbeforeBulkRestore:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:80
Adds a beforeBulkRestore hook: Model.beforeBulkRestore(fn) or Model.beforeBulkRestore(name, fn).
beforeBulkUpdate ​
staticbeforeBulkUpdate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:68
Adds a beforeBulkUpdate hook: Model.beforeBulkUpdate(fn) or Model.beforeBulkUpdate(name, fn).
beforeCount ​
staticbeforeCount:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:104
Adds a beforeCount hook: Model.beforeCount(fn) or Model.beforeCount(name, fn).
beforeCreate ​
staticbeforeCreate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:26
Adds a beforeCreate hook: Model.beforeCreate(fn) or Model.beforeCreate(name, fn).
beforeDestroy ​
staticbeforeDestroy:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:44
Adds a beforeDestroy hook: Model.beforeDestroy(fn) or Model.beforeDestroy(name, fn).
beforeFind ​
staticbeforeFind:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:86
Adds a beforeFind hook: Model.beforeFind(fn) or Model.beforeFind(name, fn).
beforeFindAfterExpandIncludeAll ​
staticbeforeFindAfterExpandIncludeAll:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:89
Adds a beforeFindAfterExpandIncludeAll hook: Model.beforeFindAfterExpandIncludeAll(fn) or Model.beforeFindAfterExpandIncludeAll(name, fn).
beforeFindAfterOptions ​
staticbeforeFindAfterOptions:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:92
Adds a beforeFindAfterOptions hook: Model.beforeFindAfterOptions(fn) or Model.beforeFindAfterOptions(name, fn).
beforeRestore ​
staticbeforeRestore:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:50
Adds a beforeRestore hook: Model.beforeRestore(fn) or Model.beforeRestore(name, fn).
beforeSave ​
staticbeforeSave:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:38
Adds a beforeSave hook: Model.beforeSave(fn) or Model.beforeSave(name, fn).
beforeSync ​
staticbeforeSync: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 ​
staticbeforeUpdate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:32
Adds a beforeUpdate hook: Model.beforeUpdate(fn) or Model.beforeUpdate(name, fn).
beforeUpsert ​
staticbeforeUpsert:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:56
Adds a beforeUpsert hook: Model.beforeUpsert(fn) or Model.beforeUpsert(name, fn).
beforeValidate ​
staticbeforeValidate:NamedHookAdder
Defined in: src/model/mixins/model-hooks.ts:17
Adds a beforeValidate hook: Model.beforeValidate(fn) or Model.beforeValidate(name, fn).
validationFailed ​
staticvalidationFailed: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 extensionFor 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 ​
wasInserted ​
Get Signature ​
get wasInserted():
boolean|undefined
Defined in: src/model/model-base.ts:41
postgrelize extensionFor 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
staticassociations():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
staticmodelName():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
staticoptions():DefinitionOptions
Defined in: src/model/model-base.ts:86
Model options after defaults were applied.
Returns ​
primaryKeyAttribute ​
Get Signature ​
get
staticprimaryKeyAttribute():string
Defined in: src/model/model-base.ts:75
First primary key attribute name.
Returns ​
string
primaryKeyAttributes ​
Get Signature ​
get
staticprimaryKeyAttributes(): readonlystring[]
Defined in: src/model/model-base.ts:81
All primary key attribute names.
Returns ​
readonly string[]
queryInterface ​
Get Signature ​
get
staticqueryInterface():QueryInterface
Defined in: src/model/mixins/model-schema.ts:77
Schema API of the owning Sequelize instance (Sequelize v6 Model.queryInterface).
Returns ​
rawAttributes ​
Get Signature ​
get
staticrawAttributes():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
staticsequelize():Sequelize
Defined in: src/model/model-base.ts:91
Sequelize instance the model belongs to.
Returns ​
tableName ​
Get Signature ​
get
statictableName():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| (keyofTAttributes&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 ​
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 ​
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? ​
Destroy options (force, hooks, query options).
Returns ​
Promise<void>
Resolves when deleted.
Example ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
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 ​
const where = user.where();Inherited from ​
ModelInstanceValues.where
addHook() ​
staticaddHook<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? ​
Hook function when a name is given.
Returns ​
MS
The model class.
Example ​
User.addHook('beforeCreate', 'normalizeEmail', async (instance: User) => {
instance.set('email', String(instance.get('email')).toLowerCase());
});See ​
addScope() ​
staticaddScope(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 ​
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 ​
User.addScope('active', { where: { active: true } });
User.addScope('olderThan', (age: number) => ({ where: { age: { [Op.gt]: age } } }));aggregate() ​
staticaggregate<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 ​
const avgPrice = await Product.aggregate('price', 'avg', { where: { active: true } });belongsTo() ​
staticbelongsTo<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 ​
Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' });See ​
belongsToMany() ​
staticbelongsToMany<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 ​
Association options with through.
Returns ​
BelongsToMany<M, T>
The association.
Example ​
Project.belongsToMany(Task, { through: 'ProjectTasks' });build() ​
staticbuild<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 ​
const user = User.build({ email: 'ada@example.com' });
await user.save();bulkBuild() ​
staticbulkBuild<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 ​
const tags = Tag.bulkBuild([{ name: 'news' }, { name: 'sports' }]);bulkCreate() ​
staticbulkCreate<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 ​
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() ​
staticcopyFrom<M>(this,rows,options?):Promise<number>
Defined in: src/model/mixins/model-postgres.ts:252
postgrelize extensionBulk-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 ​
const copied = await Task.copyFrom(
[{ title: 'first' }, { title: 'second' }],
{ columns: ['title'] },
);copyTo() ​
staticcopyTo<M>(this,options?):AsyncGenerator<Buffer<ArrayBufferLike>,void,undefined>
Defined in: src/model/mixins/model-postgres.ts:281
postgrelize extensionStreams 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 ​
for await (const chunk of User.copyTo({ attributes: ['id', 'email'], format: 'csv', header: true })) {
process.stdout.write(chunk);
}count() ​
Call Signature ​
staticcount<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 ​
const rows = await User.count({ group: ['role'] });
rows.map((r) => r.count);Call Signature ​
staticcount<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 ​
const active = await User.count({ where: { active: true } });create() ​
staticcreate<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? ​
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 ​
const user = await User.create({ email: 'ada@example.com' }, { transaction });decrement() ​
staticdecrement<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 ​
await Product.decrement({ stock: 3 }, { where: { id: 7 } });Inherited from ​
ModelInstancePersistence.decrement
deleteStatement() ​
staticdeleteStatement<M>(this,options?):WriteStatement
Defined in: src/model/mixins/model-postgres.ts:178
postgrelize extensionBuilds 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 ​
Statement for the with option.
Example ​
const done = Task.deleteStatement({ where: { done: true }, returning: true });
const removed = await Task.findAll({ with: { done }, source: 'done' });describe() ​
staticdescribe(schema?,options?):Promise<Record<string,Readonly<{allowNull:boolean;comment:string|null;defaultValue:unknown;primaryKey:boolean;special: readonlystring[];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 ​
const columns = await User.describe();destroy() ​
Call Signature ​
staticdestroy<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 ​
const removed = await Post.destroy({ where: { published: false }, returning: true });Inherited from ​
ModelInstancePersistence.destroy
Call Signature ​
staticdestroy<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? ​
Destroy options.
Returns ​
Promise<number>
Number of deleted rows.
Inherited from ​
ModelInstancePersistence.destroy
drop() ​
staticdrop(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 ​
await Task.drop({ cascade: true });dropSchema() ​
staticdropSchema(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 ​
await User.dropSchema('tenant_1');findAll() ​
staticfindAll<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 ​
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 ​
staticfindAndCountAll<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 ​
const { count, rows } = await Post.findAndCountAll({ where: { published: true }, limit: 10, offset: 20 });Call Signature ​
staticfindAndCountAll<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 ​
const { count, rows } = await Post.findAndCountAll({ group: ['status'] });findByPk() ​
Call Signature ​
staticfindByPk<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 ​
const user = await User.findByPk(42, { rejectOnEmpty: true });Call Signature ​
staticfindByPk<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 ​
const user = await User.findByPk(42, { include: [Profile] });findCreateFind() ​
staticfindCreateFind<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 ​
const [tag, created] = await Tag.findCreateFind({ where: { name: 'news' }, defaults: { color: 'red' } });findEach() ​
staticfindEach<M>(this,options?,cursor?):AsyncGenerator<M,void,undefined>
Defined in: src/model/mixins/model-postgres.ts:226
postgrelize extensionStreams 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 ​
for await (const user of User.findEach({ where: { active: true } }, { batchSize: 500 })) {
console.log(user.get('email'));
}findOne() ​
Call Signature ​
staticfindOne<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 ​
const user = await User.findOne({ where: { email: 'ada@example.com' }, rejectOnEmpty: true });Call Signature ​
staticfindOne<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? ​
Query options.
Returns ​
Promise<M | null>
Instance or null.
findOrBuild() ​
staticfindOrBuild<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 ​
const [tag, built] = await Tag.findOrBuild({ where: { name: 'news' } });
if (built) {
await tag.save();
}findOrCreate() ​
staticfindOrCreate<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 ​
const [tag, created] = await Tag.findOrCreate({ where: { name: 'news' }, defaults: { color: 'red' } });getAssociationForAlias() ​
staticgetAssociationForAlias(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 ​
const association = User.getAssociationForAlias(Post, 'posts');getAssociations() ​
staticgetAssociations(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 ​
const toPosts = User.getAssociations(Post);getAttributes() ​
staticgetAttributes():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 ​
const attributes = User.getAttributes();
Object.keys(attributes);getTableName() ​
staticgetTableName():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 ​
const table = User.getTableName();hasAlias() ​
statichasAlias(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 ​
if (User.hasAlias('posts')) {}hasHook() ​
statichasHook(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 ​
const registered = User.hasHook('beforeCreate');hasHooks() ​
statichasHooks(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 ​
const registered = User.hasHooks('afterFind');hasMany() ​
statichasMany<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 ​
User.hasMany(Post, { foreignKey: 'authorId', as: 'posts' });hasOne() ​
statichasOne<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 ​
User.hasOne(Profile, { foreignKey: 'userId' });increment() ​
staticincrement<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 ​
await Post.increment('views', { by: 1, where: { id: 5 } });Inherited from ​
ModelInstancePersistence.increment
init() ​
staticinit<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 ​
Attribute definitions.
options ​
Model options, including the sequelize instance.
Returns ​
MS
The model class.
Example ​
class Project extends Model {}
Project.init(
{ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING },
{ sequelize, modelName: 'Project', paranoid: true },
);insert() ​
staticinsert<M>(this,values,options?):Promise<M[]>
Defined in: src/model/mixins/model-postgres.ts:52
postgrelize extensionInserts 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 ​
- Model.bulkCreate for the Sequelize v6 variant.
- Bulk writes guide
Example ​
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() ​
staticinsertFrom<M>(this,source,options):Promise<M[]>
Defined in: src/model/mixins/model-postgres.ts:77
postgrelize extensionINSERT 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 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 ​
await Task.insertFrom(
Post.subquery({ attributes: ['id', 'title'], where: { published: false } }),
{ columns: ['postId', 'title'] },
);insertStatement() ​
staticinsertStatement<M>(this,rows,options?):WriteStatement
Defined in: src/model/mixins/model-postgres.ts:201
postgrelize extensionBuilds 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 ​
Statement for the with option.
Throws ​
Error without rows.
Example ​
const added = Task.insertStatement([{ title: 'write docs' }], { returning: true });
const rows = await Task.findAll({ with: { added }, source: 'added' });max() ​
staticmax<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 ​
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 ​
const highest = await Product.max('price');merge() ​
staticmerge<M>(this,options):Promise<Readonly<{rowCount:number;rows: readonlyReadonly<{action:MergeActionName;instance:M; }>[]; }>>
Defined in: src/model/mixins/model-postgres.ts:104
postgrelize extensionMERGE 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 ​
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() ​
staticmin<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 ​
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 ​
const lowest = await Product.min('price', { where: { active: true } });refreshAttributes() ​
staticrefreshAttributes():void
Defined in: src/model/mixins/model-schema.ts:139
Rebuilds the normalized attribute definitions from the model's init input.
Returns ​
void
Example ​
User.refreshAttributes();removeAttribute() ​
staticremoveAttribute(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 ​
User.removeAttribute('legacyFlag');removeHook() ​
staticremoveHook<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 ​
User.removeHook('beforeCreate', 'normalizeEmail');restore() ​
staticrestore<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 ​
await Post.restore({ where: { userId: 1 } });Inherited from ​
ModelInstancePersistence.restore
runHooks() ​
staticrunHooks(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 ​
await User.runHooks('beforeCreate', user, {});schema() ​
staticschema<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 ​
const TenantUser = User.schema('tenant_a');
await TenantUser.findAll(); // SELECT ... FROM "tenant_a"."users"
TenantUser.getTableName(); // { tableName: 'users', schema: 'tenant_a', delimiter: '.' }scope() ​
staticscope<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 ​
await User.scope('active', { method: ['olderThan', 18] }).findAll();See ​
subquery() ​
staticsubquery<M>(this,options?):Subquery
Defined in: src/model/mixins/model-postgres.ts:132
postgrelize extensionBuilds 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 expression.
Example ​
await User.findAll({ where: { id: { [Op.in]: Post.subquery({ attributes: ['userId'], where: { published: true } }) } } });sum() ​
staticsum<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 ​
const total = await Invoice.sum('amount', { where: { paid: true } });sync() ​
staticsync<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 ​
await User.sync({ alter: true });See ​
truncate() ​
statictruncate(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 ​
await Task.truncate({ restartIdentity: true, cascade: true });unscoped() ​
staticunscoped<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 ​
const everyone = await User.unscoped().findAll();update() ​
Call Signature ​
staticupdate<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 ​
const [count, rows] = await Post.update({ published: true }, { where: { userId: 1 }, returning: true });Inherited from ​
ModelInstancePersistence.update
Call Signature ​
staticupdate<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 ​
Update options; where is required.
Returns ​
Promise<[affectedCount: number]>
[affectedCount].
Throws ​
ValidationError when the new values are invalid.
Example ​
const [count] = await Post.update({ published: true }, { where: { userId: 1 } });Inherited from ​
ModelInstancePersistence.update
updateStatement() ​
staticupdateStatement<M>(this,values,options?):WriteStatement
Defined in: src/model/mixins/model-postgres.ts:155
postgrelize extensionBuilds 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 ​
Statement for the with option.
Example ​
const bumped = Task.updateStatement({ done: true }, { where: { id: 1 }, returning: true });
const rows = await Task.findAll({ with: { bumped }, source: 'bumped' });upsert() ​
staticupsert<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 ​
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 ​
const [user] = await User.upsert({ email: 'ada@example.com', name: 'Ada' }, { conflictFields: ['email'] });