Class Model<TModelAttributes, TCreationAttributes>Abstract

Type Parameters

  • TModelAttributes extends {} = any

  • TCreationAttributes extends {} = TModelAttributes

Hierarchy

  • Hooks<Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes>
    • Model

Constructors

Properties

Methods

Constructors

  • Builds a new model instance.

    Type Parameters

    • TModelAttributes extends {} = any

    • TCreationAttributes extends {} = TModelAttributes

    Parameters

    Returns Model<TModelAttributes, TCreationAttributes>

Properties

_attributes: TModelAttributes

A dummy variable that doesn't exist on the real object. This exists so Typescript can infer the type of the attributes in static functions. Don't try to access this!

Before using these, I'd tried typing out the functions without them, but Typescript fails to infer TAttributes in signatures like the below.

public static findOne<M extends Model<TAttributes>, TAttributes>(
this: { new(): M },
options: NonNullFindOptions<TAttributes>
): Promise<M>;

Deprecated

This property will become a Symbol in v7 to prevent collisions. Use Attributes instead of this property to be forward-compatible.

_creationAttributes: TCreationAttributes

A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.

Deprecated

This property will become a Symbol in v7 to prevent collisions. Use CreationAttributes instead of this property to be forward-compatible.

_model: Model<TModelAttributes, TCreationAttributes>

A dummy variable that doesn't exist on the real object. This exists so Typescript can infer the type of the attributes in static functions. Don't try to access this!

isNewRecord: boolean

Returns true if this instance has not yet been persisted to the database

sequelize: Sequelize

A reference to the sequelize instance.

_virtualAttributes: Set<string>
associations: { [key: string]: Association }

An object hash from alias to association object

Type declaration

fieldAttributeMap: { [columnName: string]: string }

A mapping of column name to attribute name

Type declaration

  • [columnName: string]: string
fieldRawAttributesMap: { [columnName: string]: BuiltModelAttributeColumOptions }

Type declaration

options: BuiltModelOptions<Model<any, any>>

The options that the model was initialized with

primaryKeyAttribute: string

The name of the primary key attribute (on the JS side).

Deprecated

This property doesn't work for composed primary keys. Use primaryKeyAttributes instead.

primaryKeyAttributes: readonly string[]

The name of the primary key attributes (on the JS side).

primaryKeyField: string

The column name of the primary key.

Deprecated

don't use this. It doesn't work with composite PKs. It may be removed in the future to reduce duplication. Use the. Use primaryKeys instead.

primaryKeys: { [attribute: string]: BuiltModelAttributeColumOptions }

Like rawAttributes, but only includes attributes that are part of the Primary Key.

Type declaration

rawAttributes: { [attribute: string]: BuiltModelAttributeColumOptions }

The attributes of the model.

Deprecated

use getAttributes for better typings.

Type declaration

sequelize?: Sequelize

Reference to the sequelize instance the model was initialized with.

Can be undefined if the Model has not been initialized yet.

tableAttributes: { [attributeName: string]: BuiltModelAttributeColumOptions }

Like getAttributes, but only includes attributes that exist in the database. i.e. virtual attributes are omitted.

Type declaration

tableName: string

The name of the database table

uniqueKeys: { [indexName: string]: { column: string; customIndex: boolean; fields: string[]; msg: string | null; name: string } }

Type declaration

  • [indexName: string]: { column: string; customIndex: boolean; fields: string[]; msg: string | null; name: string }
    • column: string
    • customIndex: boolean
    • fields: string[]
    • msg: string | null
    • name: string

      The name of the attribute

Methods

  • addHook<K>(hookType: K, name: string, fn: SequelizeHooks<Model<any, any>, TModelAttributes, TCreationAttributes>[K]): Model<TModelAttributes, TCreationAttributes>
  • addHook<K>(hookType: K, fn: SequelizeHooks<Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes>[K]): Model<TModelAttributes, TCreationAttributes>
  • Add a hook to the model

    Type Parameters

    • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • name: string

      Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.

    • fn: SequelizeHooks<Model<any, any>, TModelAttributes, TCreationAttributes>[K]

    Returns Model<TModelAttributes, TCreationAttributes>

  • Type Parameters

    • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • fn: SequelizeHooks<Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes>[K]

    Returns Model<TModelAttributes, TCreationAttributes>

  • changed<K>(key: K): boolean
  • changed<K>(key: K, dirty: boolean): void
  • changed(): false | string[]
  • If changed is called with a string it will return a boolean indicating whether the value of that key in dataValues is different from the value in _previousDataValues.

    If changed is called without an argument, it will return an array of keys that have changed.

    If changed is called with two arguments, it will set the property to dirty.

    If changed is called without an argument and no keys have changed, it will return false.

    Type Parameters

    • K extends keyof Model<TModelAttributes, TCreationAttributes>

    Parameters

    • key: K

    Returns boolean

  • Type Parameters

    • K extends keyof Model<TModelAttributes, TCreationAttributes>

    Parameters

    • key: K
    • dirty: boolean

    Returns void

  • Returns false | string[]

  • decrement<K>(fields: Partial<TModelAttributes> | K | readonly K[], options?: IncrementDecrementOptionsWithBy<TModelAttributes>): Promise<Model<TModelAttributes, TCreationAttributes>>
  • Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a

    SET column = column - X
    

    query. To get the correct value after an decrement into the Instance you should do a reload.

    instance.decrement('number') // decrement number by 1
    instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
    instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
    // `by` is ignored, since each column has its own
    // value

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • fields: Partial<TModelAttributes> | K | readonly K[]

      If a string is provided, that column is decremented by the value of by given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given

    • Optional options: IncrementDecrementOptionsWithBy<TModelAttributes>

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • Destroys the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.

    Parameters

    Returns Promise<void>

  • equals(other: Model<TModelAttributes, TCreationAttributes>): boolean
  • Check whether all values of this and other Instance are the same

    Parameters

    • other: Model<TModelAttributes, TCreationAttributes>

    Returns boolean

  • equalsOneOf(others: readonly Model<TModelAttributes, TCreationAttributes>[]): boolean
  • Check if this is equal to one of others by calling equals

    Parameters

    • others: readonly Model<TModelAttributes, TCreationAttributes>[]

    Returns boolean

  • get(options?: { clone?: boolean; plain?: boolean; raw?: boolean }): TModelAttributes
  • get<K>(key: K, options?: { clone?: boolean; plain?: boolean; raw?: boolean }): Model<TModelAttributes, TCreationAttributes>[K]
  • get(key: string, options?: { clone?: boolean; plain?: boolean; raw?: boolean }): unknown
  • If no key is given, returns all values of the instance, also invoking virtual getters.

    If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.

    Parameters

    • Optional options: { clone?: boolean; plain?: boolean; raw?: boolean }
      • Optional clone?: boolean
      • Optional plain?: boolean

        If set to true, included instances will be returned as plain objects

      • Optional raw?: boolean

        If set to true, field and virtual setters will be ignored

    Returns TModelAttributes

  • Type Parameters

    • K extends keyof Model<TModelAttributes, TCreationAttributes>

    Parameters

    • key: K
    • Optional options: { clone?: boolean; plain?: boolean; raw?: boolean }
      • Optional clone?: boolean
      • Optional plain?: boolean
      • Optional raw?: boolean

    Returns Model<TModelAttributes, TCreationAttributes>[K]

  • Parameters

    • key: string
    • Optional options: { clone?: boolean; plain?: boolean; raw?: boolean }
      • Optional clone?: boolean
      • Optional plain?: boolean
      • Optional raw?: boolean

    Returns unknown

  • getDataValue<K>(key: K): TModelAttributes[K]
  • Returns the underlying data value

    Unlike get, this method returns the value as it was retrieved, bypassing getters, cloning, virtual attributes.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      The name of the attribute to return.

    Returns TModelAttributes[K]

  • hasHook<K>(hookType: K): boolean
  • Check whether the mode has any hooks of this type

    Type Parameters

    • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K

    Returns boolean

  • hasHooks<K>(hookType: K): boolean
  • Type Parameters

    • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K

    Returns boolean

  • increment<K>(fields: Partial<TModelAttributes> | K | readonly K[], options?: IncrementDecrementOptionsWithBy<TModelAttributes>): Promise<Model<TModelAttributes, TCreationAttributes>>
  • Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a

    SET column = column + X
    

    query. To get the correct value after an increment into the Instance you should do a reload.

    instance.increment('number') // increment number by 1
    instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
    instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
    // `by` is ignored, since each column has its own
    // value

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • fields: Partial<TModelAttributes> | K | readonly K[]

      If a string is provided, that column is incremented by the value of by given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.

    • Optional options: IncrementDecrementOptionsWithBy<TModelAttributes>

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • isSoftDeleted(): boolean
  • previous(): Partial<TModelAttributes>
  • previous<K>(key: K): undefined | TModelAttributes[K]
  • Returns the previous value for key from _previousDataValues.

    Returns Partial<TModelAttributes>

  • Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

    Returns undefined | TModelAttributes[K]

  • reload(options?: FindOptions<TModelAttributes>): Promise<Model<TModelAttributes, TCreationAttributes>>
  • Refreshes the current instance in-place, i.e. update the object with current data from the DB and return the same object. This is different from doing a find(Instance.id), because that would create and return a new instance. With this method, all references to the Instance are updated with the new data and no new objects are created.

    Parameters

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • removeHook<K>(hookType: K, name: string): Model<TModelAttributes, TCreationAttributes>
  • Remove hook from the model

    Type Parameters

    • K extends keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • name: string

    Returns Model<TModelAttributes, TCreationAttributes>

  • runHooks(name: string, ...params: unknown[]): Promise<void>
  • Parameters

    • name: string
    • Rest ...params: unknown[]

    Returns Promise<void>

  • save(options?: SaveOptions<TModelAttributes>): Promise<Model<TModelAttributes, TCreationAttributes>>
  • Validates this instance, and if the validation passes, persists it to the database.

    Returns a Promise that resolves to the saved instance (or rejects with a ValidationError, which will have a property for each of the fields for which the validation failed, with the error message for that field).

    This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.

    This method is not aware of eager loaded associations. In other words, if some other model instance (child) was eager loaded with this instance (parent), and you change something in the child, calling save() will simply ignore the change that happened on the child.

    Parameters

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • set<K>(key: K, value: TModelAttributes[K], options?: SetOptions): Model<TModelAttributes, TCreationAttributes>
  • set(keys: Partial<TModelAttributes>, options?: SetOptions): Model<TModelAttributes, TCreationAttributes>
  • Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call save). In its most basic form set will update a value stored in the underlying dataValues object. However, if a custom setter function is defined for the key, that function will be called instead. To bypass the setter, you can pass raw: true in the options object.

    If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be set directly to the object passed, or used to extend dataValues, if dataValues already contain values.

    When set is called, the previous value of the field is stored and sets a changed flag(see changed).

    Set can also be used to build instances for associations, if you have values for those. When using set with associations you need to make sure the property key matches the alias of the association while also making sure that the proper include options have been set (from .build() or .findOne())

    If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K
    • value: TModelAttributes[K]
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • Parameters

    • keys: Partial<TModelAttributes>
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • setAttributes<K>(key: K, value: TModelAttributes[K], options?: SetOptions): Model<TModelAttributes, TCreationAttributes>
  • setAttributes(keys: Partial<TModelAttributes>, options?: SetOptions): Model<TModelAttributes, TCreationAttributes>
  • Alias for set.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K
    • value: TModelAttributes[K]
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • Parameters

    • keys: Partial<TModelAttributes>
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • setDataValue<K>(key: K, value: TModelAttributes[K]): void
  • Updates the underlying data value.

    Unlike set, this method skips any special behavior and directly replaces the raw value.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      The name of the attribute to update.

    • value: TModelAttributes[K]

      The new value for that attribute.

    Returns void

  • toJSON<T>(): T
  • toJSON(): object
  • Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values gotten from the DB, and apply all custom getters.

    Type Parameters

    • T extends {}

    Returns T

  • Returns object

  • update<K>(attributeName: K, value: Fn | Col | Literal | TModelAttributes[K], options?: InstanceUpdateOptions<TModelAttributes>): Promise<Model<TModelAttributes, TCreationAttributes>>
  • update(attributes: { [ key in string | number | symbol]?: Fn | Col | Literal | TModelAttributes[key] }, options?: InstanceUpdateOptions<TModelAttributes>): Promise<Model<TModelAttributes, TCreationAttributes>>
  • This is the same as calling set followed by calling save, but it only saves attributes values passed to it, making it safer.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • Parameters

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • validate(options?: ValidationOptions): Promise<void>
  • Validate the attribute of this instance according to validation rules set in the model definition.

    Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.

    Parameters

    • Optional options: ValidationOptions

    Returns Promise<void>

  • Returns an object representing the query for this instance, use with options.where

    Parameters

    • Optional checkVersion: boolean

      include version attribute in where hash

    Returns WhereOptions<any>

  • _injectDependentVirtualAttributes(attributes: string[]): string[]
  • Private

    Parameters

    • attributes: string[]

    Returns string[]

  • addHook<H, K>(this: HooksStatic<H>, hookType: K, name: string, fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]): HooksCtor<H>
  • addHook<H, K>(this: HooksStatic<H>, hookType: K, fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]): HooksCtor<H>
  • Add a hook to the model

    Type Parameters

    Parameters

    • this: HooksStatic<H>
    • hookType: K
    • name: string

      Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.

    • fn: SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>[K]

    Returns HooksCtor<H>

  • Type Parameters

    Parameters

    Returns HooksCtor<H>

  • afterBulkSync(name: string, fn: ((options: SyncOptions) => HookReturn)): void
  • afterBulkSync(fn: ((options: SyncOptions) => HookReturn)): void
  • A hook that is run after sequelize.sync call

    Parameters

    • name: string
    • fn: ((options: SyncOptions) => HookReturn)

      A callback function that is called with options passed to sequelize.sync

    Returns void

  • Parameters

    Returns void

  • A hook that is run after a find (select) query

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • name: string
    • fn: ((instancesOrInstance: null | M | readonly M[], options: FindOptions<Attributes<M>>) => HookReturn)

      A callback function that is called with instance(s), options

    Returns void

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns void

  • afterSync(name: string, fn: ((options: SyncOptions) => HookReturn)): void
  • afterSync(fn: ((options: SyncOptions) => HookReturn)): void
  • A hook that is run after Model.sync call

    Parameters

    • name: string
    • fn: ((options: SyncOptions) => HookReturn)

      A callback function that is called with options passed to Model.sync

    Returns void

  • Parameters

    Returns void

  • afterValidate<M>(this: ModelStatic<M>, name: string, fn: ((instance: M, options: ValidationOptions) => HookReturn)): void
  • afterValidate<M>(this: ModelStatic<M>, fn: ((instance: M, options: ValidationOptions) => HookReturn)): void
  • A hook that is run after validation

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • name: string
    • fn: ((instance: M, options: ValidationOptions) => HookReturn)

      A callback function that is called with instance, options

        • (instance: M, options: ValidationOptions): HookReturn
        • Parameters

          • instance: M
          • options: ValidationOptions

          Returns HookReturn

    Returns void

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • fn: ((instance: M, options: ValidationOptions) => HookReturn)
        • (instance: M, options: ValidationOptions): HookReturn
        • Parameters

          • instance: M
          • options: ValidationOptions

          Returns HookReturn

    Returns void

  • Run an aggregation method on the specified field.

    Returns the aggregate result cast to dataType, unless options.plain is false, in which case the complete data result is returned.

    Type Parameters

    • T

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • attribute: keyof Attributes<M> | "*"

      The attribute to aggregate over. Can be a field name or '*'

    • aggregateFunction: string

      The function to use for aggregation, e.g. sum, max etc.

    • Optional options: AggregateOptions<T, Attributes<M>>

    Returns Promise<T>

  • beforeBulkSync(name: string, fn: ((options: SyncOptions) => HookReturn)): void
  • beforeBulkSync(fn: ((options: SyncOptions) => HookReturn)): void
  • A hook that is run before sequelize.sync call

    Parameters

    • name: string
    • fn: ((options: SyncOptions) => HookReturn)

      A callback function that is called with options passed to sequelize.sync

    Returns void

  • Parameters

    Returns void

  • beforeSync(name: string, fn: ((options: SyncOptions) => HookReturn)): void
  • beforeSync(fn: ((options: SyncOptions) => HookReturn)): void
  • A hook that is run before Model.sync call

    Parameters

    • name: string
    • fn: ((options: SyncOptions) => HookReturn)

      A callback function that is called with options passed to Model.sync

    Returns void

  • Parameters

    Returns void

  • beforeValidate<M>(this: ModelStatic<M>, name: string, fn: ((instance: M, options: ValidationOptions) => HookReturn)): void
  • beforeValidate<M>(this: ModelStatic<M>, fn: ((instance: M, options: ValidationOptions) => HookReturn)): void
  • A hook that is run before validation

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • name: string
    • fn: ((instance: M, options: ValidationOptions) => HookReturn)

      A callback function that is called with instance, options

        • (instance: M, options: ValidationOptions): HookReturn
        • Parameters

          • instance: M
          • options: ValidationOptions

          Returns HookReturn

    Returns void

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • fn: ((instance: M, options: ValidationOptions) => HookReturn)
        • (instance: M, options: ValidationOptions): HookReturn
        • Parameters

          • instance: M
          • options: ValidationOptions

          Returns HookReturn

    Returns void

  • Creates an association between this (the source) and the provided target. The foreign key is added on the source Model.

    See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.

    Example

    Profile.belongsTo(User)
    

    Returns

    The newly defined association (also available in associations).

    Type Parameters

    • S extends Model<any, any, S>

    • T extends Model<any, any, T>

    • SKey extends string

    • TKey extends string

    Parameters

    Returns BelongsTo<S, T, SKey, TKey>

  • Create an N:M association with a join table. Defining through is required. The foreign key is added on the through model.

    See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.

    Example

    // Automagically generated join model
    User.belongsToMany(Project, { through: 'UserProjects' })

    // Join model with additional attributes
    const UserProjects = sequelize.define('UserProjects', {
    started: Sequelize.BOOLEAN
    })
    User.belongsToMany(Project, { through: UserProjects })

    Returns

    The newly defined association (also available in associations).

    Type Parameters

    • S extends Model<any, any, S>

    • T extends Model<any, any, T>

    • ThroughModel extends Model<any, any, ThroughModel>

    • SKey extends string

    • TKey extends string

    Parameters

    Returns BelongsToMany<S, T, ThroughModel, SKey, TKey>

  • Builds a new model instance. Unlike create, the instance is not persisted, you need to call save yourself.

    Returns

    The created instance.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns M

  • Builds multiple new model instances. Unlike create, the instances are not persisted, you need to call save yourself.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns M[]

  • Creates and inserts multiple instances in bulk.

    The promise resolves with an array of instances.

    Please note that, depending on your dialect, the resulting instances may not accurately represent the state of their rows in the database. This is because MySQL and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records. To obtain the correct data for the newly created instance, you will need to query for them again.

    If validation fails, the promise is rejected with AggregateError

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<M[]>

  • Count number of records if group by is used

    Returns

    Returns count for each group and the projected attributes.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • options: { attributes?: FindAttributeOptions; benchmark?: boolean; col?: string; distinct?: boolean; group: GroupOption; include?: AllowArray<Includeable>; logging?: boolean | ((sql: string, timing?: number) => void); paranoid?: boolean; transaction?: null | Transaction; useMaster?: boolean; where?: WhereOptions<Attributes<M>> }
      • Optional attributes?: FindAttributeOptions

        If an array: a list of the attributes that you want to select. Attributes can also be raw SQL (literal), fn, and col

        To rename an attribute, you can pass an array, with two elements:

        • The first is the name of the attribute (or literal, fn, col),
        • and the second is the name to give to that attribute in the returned instance.

        If include is used: selects all the attributes of the model, plus some additional ones. Useful for aggregations.

        Example

        { attributes: { include: [[literal('COUNT(id)'), 'total']] }
        

        If exclude is used: selects all the attributes of the model, except the one specified in exclude. Useful for security purposes

        Example

        { attributes: { exclude: ['password'] } }
        
      • Optional benchmark?: boolean

        Pass query execution time in milliseconds as second argument to logging function (options.logging).

      • Optional col?: string

        Column on which COUNT() should be applied

      • Optional distinct?: boolean

        Apply COUNT(DISTINCT(col))

      • group: GroupOption

        GROUP BY in sql Used in conjunction with attributes.

        See

        Projectable

      • Optional include?: AllowArray<Includeable>

        Include options. See find for details

      • Optional logging?: boolean | ((sql: string, timing?: number) => void)

        A function that gets executed while running the query to log the sql.

      • Optional paranoid?: boolean

        If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.

        Only applies if paranoid is true for the model.

        Default

        true

      • Optional transaction?: null | Transaction

        The transaction in which this query must be run.

        If CLS is enabled and a transaction is running in the current CLS context, that transaction will be used, unless null or a Transaction is manually specified here.

      • Optional useMaster?: boolean

        Force the query to use the write pool, regardless of the query type.

        Default

        false

      • Optional where?: WhereOptions<Attributes<M>>

        The WHERE clause. Can be many things from a hash of attributes to raw SQL.

        Visit https://sequelize.org/docs/v7/core-concepts/model-querying-basics/ for more information.

    Returns Promise<GroupedCountResultItem[]>

  • Count the number of records matching the provided where clause.

    If you provide an include option, the number of matching associations will be counted instead.

    Returns

    Returns count for each group and the projected attributes.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<number>

  • create<M, O>(this: ModelStatic<M>, record?: CreationAttributes<M>, options?: O): Promise<O extends { returning: false } | { ignoreDuplicates: true } ? void : M>
  • Decrements the value of one or more attributes.

    Works like increment

    Returns

    an array of affected rows and affected count with options.returning true, whenever supported by dialect

    Since

    4.36.0

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<M>

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<M>

  • describe(schema?: string, options?: Omit<QueryOptions, "type">): Promise<object>
  • Runs a 'describe' query on the table.

    Returns

    a promise that resolves with a mapping of attributes and their types.

    Parameters

    • Optional schema: string
    • Optional options: Omit<QueryOptions, "type">

    Returns Promise<object>

  • Deletes multiple instances, or set their deletedAt timestamp to the current time if paranoid is enabled.

    Returns

    The number of destroyed rows

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<number>

  • Drop the table represented by this Model

    Parameters

    Returns Promise<void>

  • Finds all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for pagination.

    Model.findAndCountAll({
    where: ...,
    limit: 12,
    offset: 12
    }).then(result => {
    ...
    })

    In the above example, result.rows will contain rows 13 through 24, while result.count will return the total number of rows that matched your query.

    When you add includes, only those which are required (either because they have a where clause, or because required` is explicitly set to true on the include) will be added to the count part.

    Suppose you want to find all users who have a profile attached:

    User.findAndCountAll({
    include: [
    { model: Profile, required: true}
    ],
    limit: 3
    });

    Because the include for Profile has required set it will result in an inner join, and only the users who have a profile will be counted. If we remove required from the include, both users with and without profiles will be counted

    This function also support grouping, when group is provided, the count will be an array of objects containing the count for each group and the projected attributes.

    User.findAndCountAll({
    group: 'type'
    });

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<{ count: number; rows: M[] }>

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • options: { attributes?: FindAttributeOptions; benchmark?: boolean; bind?: BindOrReplacements; col?: string; distinct?: boolean; fieldMap?: FieldMap; group: GroupOption; groupedLimit?: unknown; having?: WhereOptions<any>; include?: AllowArray<Includeable>; indexHints?: IndexHint[]; instance?: Model<any, any>; limit?: Nullish<number | Literal>; lock?: boolean | LOCK | { level: LOCK; of: ModelStatic<Model<any, any>> }; logging?: boolean | ((sql: string, timing?: number) => void); mapToModel?: boolean; nest?: boolean; offset?: number | Literal; order?: Order; paranoid?: boolean; plain?: boolean; raw?: boolean; rejectOnEmpty?: boolean | Error; replacements?: BindOrReplacements; retry?: RetryOptions; searchPath?: string; skipLocked?: boolean; subQuery?: boolean; transaction?: null | Transaction; type?: string; useMaster?: boolean; where?: WhereOptions<Attributes<M>> }
      • Optional attributes?: FindAttributeOptions

        If an array: a list of the attributes that you want to select. Attributes can also be raw SQL (literal), fn, and col

        To rename an attribute, you can pass an array, with two elements:

        • The first is the name of the attribute (or literal, fn, col),
        • and the second is the name to give to that attribute in the returned instance.

        If include is used: selects all the attributes of the model, plus some additional ones. Useful for aggregations.

        Example

        { attributes: { include: [[literal('COUNT(id)'), 'total']] }
        

        If exclude is used: selects all the attributes of the model, except the one specified in exclude. Useful for security purposes

        Example

        { attributes: { exclude: ['password'] } }
        
      • Optional benchmark?: boolean

        Pass query execution time in milliseconds as second argument to logging function (options.logging).

      • Optional bind?: BindOrReplacements

        Either an object of named parameter bindings in the format $param or an array of unnamed values to bind to $1, $2, etc in your SQL.

      • Optional col?: string

        Column on which COUNT() should be applied

      • Optional distinct?: boolean

        Apply COUNT(DISTINCT(col))

      • Optional fieldMap?: FieldMap

        Map returned fields to arbitrary names for SELECT query type if options.fieldMaps is present.

      • group: GroupOption

        GROUP BY in sql Used in conjunction with attributes.

        See

        Projectable

      • Optional groupedLimit?: unknown
      • Optional having?: WhereOptions<any>

        Select group rows after groups and aggregates are computed.

      • Optional include?: AllowArray<Includeable>

        Include options. See find for details

      • Optional indexHints?: IndexHint[]

        MySQL only.

      • Optional instance?: Model<any, any>

        A sequelize instance used to build the return instance

      • Optional limit?: Nullish<number | Literal>

        Limits how many items will be retrieved by the operation.

        If limit and include are used together, Sequelize will turn the subQuery option on by default. This is done to ensure that limit only impacts the Model on the same level as the limit option.

        You can disable this behavior by explicitly setting subQuery: false, however limit will then affect the total count of returned values, including eager-loaded associations, instead of just one table.

        Example

        // in the following query, `limit` only affects the "User" model.
        // This will return 2 users, each including all of their projects.
        User.findAll({
        limit: 2,
        include: [User.associations.projects],
        });

        Example

        // in the following query, `limit` affects the total number of returned values, eager-loaded associations included.
        // This may return 2 users, each with one project,
        // or 1 user with 2 projects.
        User.findAll({
        limit: 2,
        include: [User.associations.projects],
        subQuery: false,
        });
      • Optional lock?: boolean | LOCK | { level: LOCK; of: ModelStatic<Model<any, any>> }

        Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. See LOCK.

      • Optional logging?: boolean | ((sql: string, timing?: number) => void)

        A function that gets executed while running the query to log the sql.

      • Optional mapToModel?: boolean

        Map returned fields to model's fields if options.model or options.instance is present. Mapping will occur before building the model instance.

      • Optional nest?: boolean

        If true, transforms objects with . separated property names into nested objects using dottie.js. For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When nest is true, the query type is assumed to be 'SELECT', unless otherwise specified

        Default

        false

      • Optional offset?: number | Literal

        Skip the first n items of the results.

      • Optional order?: Order

        Specifies an ordering. If a string is provided, it will be escaped.

        Using an array, you can provide several attributes / functions to order by. Each element can be further wrapped in a two-element array:

        • The first element is the column / function to order by,
        • the second is the direction.

        Example

        order: [['name', 'DESC']].

        The attribute will be escaped, but the direction will not.

      • Optional paranoid?: boolean

        If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.

        Only applies if paranoid is true for the model.

        Default

        true

      • Optional plain?: boolean

        Sets the query type to SELECT and return a single row

      • Optional raw?: boolean

        Return raw result. See query for more information.

      • Optional rejectOnEmpty?: boolean | Error

        Throws an error if the query would return 0 results.

      • Optional replacements?: BindOrReplacements

        Either an object of named parameter replacements in the format :param or an array of unnamed replacements to replace ? in your SQL.

      • Optional retry?: RetryOptions
      • Optional searchPath?: string

        An optional parameter to specify the schema search_path (Postgres only)

      • Optional skipLocked?: boolean

        Skip locked rows. Only supported in Postgres.

      • Optional subQuery?: boolean

        Use sub queries (internal).

        If unspecified, this will true by default if limit is specified, and false otherwise. See limit for more information.

      • Optional transaction?: null | Transaction

        The transaction in which this query must be run.

        If CLS is enabled and a transaction is running in the current CLS context, that transaction will be used, unless null or a Transaction is manually specified here.

      • Optional type?: string

        The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but Sequelize.QueryTypes is provided as convenience shortcuts.

      • Optional useMaster?: boolean

        Force the query to use the write pool, regardless of the query type.

        Default

        false

      • Optional where?: WhereOptions<Attributes<M>>

        The WHERE clause. Can be many things from a hash of attributes to raw SQL.

        Visit https://sequelize.org/docs/v7/core-concepts/model-querying-basics/ for more information.

    Returns Promise<{ count: GroupedCountResultItem[]; rows: M[] }>

  • A more performant findOrCreate that will not start its own transaction or savepoint (at least not in postgres)

    It will execute a find call, attempt to create if empty, then attempt to find again if a unique constraint fails.

    The successful result of the promise will be the tuple [instance, initialized].

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[entity: M, created: boolean]>

  • Find an entity that matches the query, or build (but don't save) the entity if none is found. The successful result of the promise will be the tuple [instance, initialized].

    See also findOrCreate for a version that immediately saves the new entity.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[entity: M, built: boolean]>

  • Find an entity that matches the query, or create the entity if none is found The successful result of the promise will be the tuple [instance, initialized].

    If no transaction is passed in the options object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call. However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of TimeoutError will be thrown instead.

    If a transaction is passed, a savepoint will be created instead, and any unique constraint violation will be handled internally.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[entity: M, created: boolean]>

  • Returns the association for which the target matches the 'target' parameter, and the alias ("as") matches the 'alias' parameter

    Throws if no such association were found.

    Type Parameters

    • S extends Model<any, any, S>

    • T extends Model<any, any, T>

    Parameters

    Returns Association<S, T, string, NormalizedAssociationOptions<string>>

  • Returns the initial model, the one returned by init or define, before any scope or schema was applied.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns ModelStatic<M>

  • getTableName(): string | { delimiter: string; schema: string; tableName: string }
  • Get the table name of the model, including the schema. The method will return The name as a string if the model has no schema, or an object with tableName, schema and delimiter properties.

    Returns string | { delimiter: string; schema: string; tableName: string }

  • hasAlias(alias: string): boolean
  • Checks whether an association with this name has already been registered.

    Returns

    Parameters

    • alias: string

    Returns boolean

  • Check whether the mode has any hooks of this type

    Type Parameters

    • H extends Hooks<Model<any, any>, any, any, H>

    Parameters

    Returns boolean

  • Type Parameters

    • H extends Hooks<Model<any, any>, any, any, H>

    Parameters

    Returns boolean

  • Defines a 1:n association between two models. The foreign key is added on the target model.

    See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.

    Example

    Profile.hasMany(User)
    

    Returns

    The newly defined association (also available in associations).

    Type Parameters

    • S extends Model<any, any, S>

    • T extends Model<any, any, T>

    • SKey extends string

    • TKey extends string

    Parameters

    • this: ModelStatic<S>
    • target: ModelStatic<T>

      The model that will be associated with a hasMany relationship

    • Optional options: HasManyOptions<SKey, TKey>

      Options for the association

    Returns HasMany<S, T, SKey, TKey, any>

  • Creates a 1:1 association between this model (the source) and the provided target. The foreign key is added on the target model.

    See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.

    Example

    User.hasOne(Profile)
    

    Returns

    The newly defined association (also available in associations).

    Type Parameters

    • S extends Model<any, any, S>

    • T extends Model<any, any, T>

    • SKey extends string

    • TKey extends string

    Parameters

    • this: ModelStatic<S>
    • target: ModelStatic<T>

      The model that will be associated with hasOne relationship

    • Optional options: HasOneOptions<SKey, TKey>

      hasOne association options

    Returns HasOne<S, T, SKey, TKey, any>

  • Increments the value of one or more attributes.

    The increment is done using a SET column = column + X WHERE foo = 'bar' query.

    Example

    increment number by 1 ```javascript Model.increment('number', { where: { foo: 'bar' }); ```

    Example

    increment number and count by 2 ```javascript Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } }); ```

    Example

    increment answer by 42, and decrement tries by 1 ```javascript // `by` cannot be used, as each attribute specifies its own value Model.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } }); ```

    Returns

    an array of affected rows and affected count with options.returning true, whenever supported by dialect

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[affectedRows: M[]]>

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[affectedRows: M[]]>

  • refreshAttributes(): void
  • Refreshes the Model's attribute definition.

    Returns void

  • removeAttribute(attribute: string): void
  • Remove attribute from model definition. Only use if you know what you're doing.

    Parameters

    • attribute: string

    Returns void

  • removeHook<H>(this: HooksStatic<H>, hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, CreationAttributes<H>>, name: string): HooksCtor<H>
  • Remove hook from the model

    Type Parameters

    • H extends Hooks<Model<any, any>, any, any, H>

    Parameters

    Returns HooksCtor<H>

  • schema<M>(this: ModelStatic<M>, schema: string, options?: string | { schemaDelimiter?: string }): ModelStatic<M>
  • Deprecated

    this method has been renamed to withSchema to emphasise the fact that this method does not mutate the model and instead returns a new one.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • schema: string
    • Optional options: string | { schemaDelimiter?: string }

    Returns ModelStatic<M>

  • Creates this table in the database, if it does not already exist.

    Works like sync, but only this model is synchronised.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<M>

  • Destroys all instances of the model. This is a convenient method for MyModel.destroy({ truncate: true }).

    Danger: This will completely empty your table!

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<void>

  • Updates multiple instances that match the where options.

    The promise resolves with an array of one or two elements:

    • The first element is always the number of affected rows,
    • the second element is the list of affected entities (only supported in postgres and mssql with returning true.)

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

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

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[affectedCount: number]>

  • Inserts or updates a single entity. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise, you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.

    Implementation details:

    • MySQL - Implemented as a single query INSERT values ON DUPLICATE KEY UPDATE values
    • PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN unique_constraint UPDATE
    • SQLite - Implemented as two queries INSERT; UPDATE. This means that the update is executed regardless of whether the row already existed or not

    Note: SQLite returns null for created, no matter if the row was created or updated. This is because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know whether the row was inserted or not.

    Returns

    an array with two elements, the first being the new record and the second being true if it was just created or false if it already existed (except on Postgres and SQLite, which can't detect this and will always return null instead of a boolean).

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns Promise<[entity: M, created: null | boolean]>

  • Returns the base model, with its initial scope.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns ModelStatic<M>

  • Returns a copy of this model with the corresponding table located in the specified schema.

    For postgres, this will actually place the schema in front of the table name ("schema"."tableName"), while the schema will be prepended to the table name for mysql and sqlite ('schema.tablename').

    This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important to call sync (or use migrations!) for each model created by this method to ensure the models are created in the correct schema.

    If a single default schema per model is needed, set the schema instead.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    Returns ModelStatic<M>

  • Creates a copy of this model, with one or more scopes applied.

    See https://sequelize.org/docs/v7/other-topics/scopes/ to learn more about scopes.

    Returns

    A copy of this model, with the scopes applied.

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

    • this: ModelStatic<M>
    • Optional scopes: AllowReadonlyArray<string | ScopeOptions> | WhereAttributeHash<M>

      The scopes to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, pass an object, with a method property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.

    Returns ModelStatic<M>

Generated using TypeDoc