Class Model<TModelAttributes, TCreationAttributes>Abstract

A Model represents a table in the database. Instances of this class represent a database row.

Type Parameters

  • TModelAttributes extends {} = any
  • TCreationAttributes extends {} = TModelAttributes

Hierarchy (View Summary)

Constructors

Properties

Accessors

Methods

Constructors

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>;

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.

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

dataValues: TModelAttributes

Object that contains underlying model data

isNewRecord: boolean

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

addHook: LegacyAddAnyHookFunction<ModelHooks<Model<any, any>, any>> = ...
afterAssociate: LegacyAddHookFunction<
    (
        data: AfterAssociateEventData,
        options: AssociationOptions<any>,
    ) => AsyncHookReturn,
> = ...
afterBulkCreate: LegacyAddHookFunction<
    (
        instances: readonly Model<any, any>[],
        options: BulkCreateOptions<any>,
    ) => AsyncHookReturn,
> = ...
afterBulkDestroy: LegacyAddHookFunction<
    (options: DestroyOptions<any>) => AsyncHookReturn,
> = ...
afterBulkRestore: LegacyAddHookFunction<
    (options: RestoreOptions<any>) => AsyncHookReturn,
> = ...
afterBulkUpdate: LegacyAddHookFunction<
    (options: UpdateOptions<any>) => AsyncHookReturn,
> = ...
afterCreate: LegacyAddHookFunction<
    (attributes: Model, options: CreateOptions<any>) => AsyncHookReturn,
> = ...
afterDestroy: LegacyAddHookFunction<
    (instance: Model, options: InstanceDestroyOptions) => AsyncHookReturn,
> = ...
afterFind: LegacyAddHookFunction<
    (
        instancesOrInstance:
            | null
            | Model<any, any>
            | readonly Model<any, any>[],
        options: FindOptions<any>,
    ) => AsyncHookReturn,
> = ...
afterRestore: LegacyAddHookFunction<
    (instance: Model, options: InstanceRestoreOptions) => AsyncHookReturn,
> = ...
afterSave: LegacyAddHookFunction<
    (
        instance: Model,
        options: InstanceUpdateOptions<any> | CreateOptions<any>,
    ) => AsyncHookReturn,
> = ...
afterSync: LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn> = ...
afterUpdate: LegacyAddHookFunction<
    (
        instance: Model,
        options: InstanceUpdateOptions<any>,
    ) => AsyncHookReturn,
> = ...
afterUpsert: LegacyAddHookFunction<
    (
        attributes: [Model<any, any>, null | boolean],
        options: UpsertOptions<any>,
    ) => AsyncHookReturn,
> = ...
afterValidate: LegacyAddHookFunction<
    (instance: Model, options: ValidationOptions) => AsyncHookReturn,
> = ...
beforeAssociate: LegacyAddHookFunction<
    (
        data: BeforeAssociateEventData,
        options: AssociationOptions<any>,
    ) => AsyncHookReturn,
> = ...
beforeBulkCreate: LegacyAddHookFunction<
    (
        instances: Model<any, any>[],
        options: BulkCreateOptions<any>,
    ) => AsyncHookReturn,
> = ...
beforeBulkDestroy: LegacyAddHookFunction<
    (options: DestroyOptions<any>) => AsyncHookReturn,
> = ...
beforeBulkRestore: LegacyAddHookFunction<
    (options: RestoreOptions<any>) => AsyncHookReturn,
> = ...
beforeBulkUpdate: LegacyAddHookFunction<
    (options: UpdateOptions<any>) => AsyncHookReturn,
> = ...
beforeCount: LegacyAddHookFunction<
    (options: CountOptions<any>) => AsyncHookReturn,
> = ...
beforeCreate: LegacyAddHookFunction<
    (attributes: Model, options: CreateOptions<any>) => AsyncHookReturn,
> = ...
beforeDestroy: LegacyAddHookFunction<
    (instance: Model, options: InstanceDestroyOptions) => AsyncHookReturn,
> = ...
beforeFind: LegacyAddHookFunction<
    (options: FindOptions<any>) => AsyncHookReturn,
> = ...
beforeFindAfterExpandIncludeAll: LegacyAddHookFunction<
    (options: FindOptions<any>) => AsyncHookReturn,
> = ...
beforeFindAfterOptions: LegacyAddHookFunction<
    (options: FindOptions<any>) => AsyncHookReturn,
> = ...
beforeRestore: LegacyAddHookFunction<
    (instance: Model, options: InstanceRestoreOptions) => AsyncHookReturn,
> = ...
beforeSave: LegacyAddHookFunction<
    (
        instance: Model,
        options: InstanceUpdateOptions<any> | CreateOptions<any>,
    ) => AsyncHookReturn,
> = ...
beforeSync: LegacyAddHookFunction<(options: SyncOptions) => AsyncHookReturn> = ...
beforeUpdate: LegacyAddHookFunction<
    (
        instance: Model,
        options: InstanceUpdateOptions<any>,
    ) => AsyncHookReturn,
> = ...
beforeUpsert: LegacyAddHookFunction<
    (attributes: Model, options: UpsertOptions<any>) => AsyncHookReturn,
> = ...
beforeValidate: LegacyAddHookFunction<
    (instance: Model, options: ValidationOptions) => AsyncHookReturn,
> = ...
hasHook: <HookName extends keyof ModelHooks<Model<any, any>, any>>(
    this: { hooks: HookHandler<ModelHooks<Model<any, any>, any>> },
    hookName: HookName,
) => boolean = ...
hasHooks: <HookName extends keyof ModelHooks<Model<any, any>, any>>(
    this: { hooks: HookHandler<ModelHooks<Model<any, any>, any>> },
    hookName: HookName,
) => boolean = ...
removeHook: <HookName extends keyof ModelHooks<Model<any, any>, any>>(
    this: { hooks: HookHandler<ModelHooks<Model<any, any>, any>> },
    hookName: HookName,
    listenerNameOrListener: string | ModelHooks<Model<any, any>, any>[HookName],
) => void = ...
runHooks: LegacyRunHookFunction<ModelHooks<Model<any, any>, any>, void> = ...
validationFailed: LegacyAddHookFunction<
    (
        instance: Model,
        options: ValidationOptions,
        error: unknown,
    ) => AsyncHookReturn,
> = ...

Accessors

  • get primaryKeyAttribute(): null | string

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

    Returns null | string

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

  • get primaryKeyField(): null | string

    The column name of the primary key.

    Returns null | string

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

  • get uniqueKeys(): any

    Unique indexes that can be declared as part of a CREATE TABLE query.

    Returns any

    prefer using getIndexes, this will eventually be removed.

Methods

  • 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 string | number | symbol

    Parameters

    • key: K

    Returns boolean

  • 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 string | number | symbol

    Parameters

    • key: K
    • dirty: boolean

    Returns void

  • 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.

    Returns false | string[]

  • Check whether all values of this and other Instance are the same

    Parameters

    • other: this

    Returns boolean

  • Returns the underlying data value

    Unlike Model#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]

  • 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

    Returns this

  • 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.

    Parameters

    Returns this

  • Updates the underlying data value.

    Unlike Model#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

  • 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

  • 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.

    Returns object

  • 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>

    Parameters

    Returns Promise<M[]>

  • Count number of records if group by is used

    Type Parameters

    • M extends Model<any, any>

    Parameters

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

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

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

        • The first is the name of the attribute (or literal, fn, col, cast),
        • 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.

        { 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

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

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

      • Optionalcol?: string

        Column on which COUNT() should be applied

      • Optionalconnection?: null | AbstractConnection

        The connection on which this query must be run. Mutually exclusive with Transactionable.transaction.

        Can be used to ensure that a query is run on the same connection as a previous query, which is useful when configuring session options.

        Specifying this option takes precedence over CLS Transactions. If a transaction is running in the current AsyncLocalStorage context, it will be ignored in favor of the specified connection.

      • OptionalcountGroupedRows?: boolean

        Count number of records returned by group by Used in conjunction with group.

      • Optionaldistinct?: boolean

        Apply COUNT(DISTINCT(col))

      • group: GroupOption

        GROUP BY in sql Used in conjunction with attributes.

        Projectable

      • Optionalinclude?: AllowArray<Includeable>

        Include options. See find for details

      • Optionallogging?: false | (sql: string, timing?: number) => void

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

      • OptionalmaxExecutionTimeHintMs?: number

        This sets the max execution time for MySQL.

      • Optionalparanoid?: boolean

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

        Only applies if InitOptions.paranoid is true for the model.

        true
        
      • Optionaltransaction?: null | Transaction

        The transaction in which this query must be run. Mutually exclusive with Transactionable.connection.

        If the Sequelize disableClsTransactions option has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.

      • OptionaluseMaster?: boolean

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

        false
        
      • Optionalwhere?: 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[]>

    Returns count for each group and the projected attributes.

  • 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.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<number>

    Returns count for each group and the projected attributes.

  • 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>

    Parameters

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

  • 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>

    Parameters

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

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

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

        • The first is the name of the attribute (or literal, fn, col, cast),
        • 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.

        { 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

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

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

      • Optionalbind?: 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.

      • Optionalcol?: string

        Column on which COUNT() should be applied

      • Optionalconnection?: null | AbstractConnection

        The connection on which this query must be run. Mutually exclusive with Transactionable.transaction.

        Can be used to ensure that a query is run on the same connection as a previous query, which is useful when configuring session options.

        Specifying this option takes precedence over CLS Transactions. If a transaction is running in the current AsyncLocalStorage context, it will be ignored in favor of the specified connection.

      • OptionalcountGroupedRows?: boolean

        Count number of records returned by group by Used in conjunction with group.

      • Optionaldistinct?: boolean

        Apply COUNT(DISTINCT(col))

      • OptionalfieldMap?: 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.

        Projectable

      • OptionalgroupedLimit?: unknown
      • Optionalhaving?: WhereOptions<any>

        Select group rows after groups and aggregates are computed.

      • Optionalinclude?: AllowArray<Includeable>

        Include options. See find for details

      • OptionalindexHints?: IndexHint[]

        MySQL only.

      • Optionalinstance?: Model<any, any>

        A sequelize instance used to build the return instance

      • Optionallimit?: number | Nullish | 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.

        // 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],
        });
        // 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,
        });
      • Optionallock?: 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.

      • Optionallogging?: false | (sql: string, timing?: number) => void

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

      • OptionalmapToModel?: boolean

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

      • OptionalmaxExecutionTimeHintMs?: number

        This sets the max execution time for MySQL.

      • OptionalminifyAliases?: boolean

        Controls whether aliases are minified in this query. This overrides the global option

      • Optionalnest?: 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

        false
        
      • Optionaloffset?: number | Nullish | Literal

        Skip the first n items of the results.

      • Optionalorder?: 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.
        `order: [['name', 'DESC']]`.

        The attribute will be escaped, but the direction will not.
      • Optionalparanoid?: boolean

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

        Only applies if InitOptions.paranoid is true for the model.

        true
        
      • Optionalplain?: boolean

        Sets the query type to SELECT and return a single row

      • Optionalraw?: boolean

        Return raw result. See Sequelize#query for more information.

      • OptionalrejectOnEmpty?: boolean | Error

        Throws an error if the query would return 0 results.

      • Optionalreplacements?: BindOrReplacements

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

      • Optionalretry?: Options
      • OptionalsearchPath?: string

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

      • OptionalskipLocked?: boolean

        Skip locked rows. Only supported in Postgres.

      • OptionalsubQuery?: boolean

        Use sub queries (internal).

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

      • OptionalsupportsSearchPath?: boolean

        If false do not prepend the query with the search_path (Postgres only)

      • OptionaltableHints?: TableHints[]

        Use a table hint for the query, only supported in MSSQL.

      • Optionaltransaction?: null | Transaction

        The transaction in which this query must be run. Mutually exclusive with Transactionable.connection.

        If the Sequelize disableClsTransactions option has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.

      • Optionaltype?: 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.

      • OptionaluseMaster?: boolean

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

        false
        
      • Optionalwhere?: 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[] }>

  • Find an entity that matches the query, or Model.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>

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

  • Checks whether an association with this name has already been registered.

    Parameters

    • alias: string

    Returns boolean

  • Increments the value of one or more attributes.

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

    Type Parameters

    • M extends Model<any, any>

    Parameters

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

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

    Model.increment('number', { where: { foo: 'bar' });
    
    Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
    
    // `by` cannot be used, as each attribute specifies its own value
    Model.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } });
  • Increments the value of one or more attributes.

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

    Type Parameters

    • M extends Model<any, any>

    Parameters

    • this: ModelStatic<M>
    • fields: { [key in string | number | symbol]?: number }

      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 an object is provided, each key is incremented by the corresponding value, by is ignored.

    • options: IncrementDecrementOptions<Attributes<M>>

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

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

    Model.increment('number', { where: { foo: 'bar' });
    
    Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
    
    // `by` cannot be used, as each attribute specifies its own value
    Model.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } });
  • Remove attribute from model definition. Only use if you know what you're doing.

    Parameters

    • attribute: string

    Returns void

  • 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.

    Type Parameters

    • M extends Model<any, any>

    Parameters

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

    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).

  • 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 Model.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 ModelOptions.schema instead.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns ModelStatic<M>