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

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

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

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

    Parameters

    • other: Model<TModelAttributes, TCreationAttributes>

    Returns boolean

  • Check if this is equal to one of others by calling equals

    Parameters

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

    Returns boolean

  • If no key is given, returns all values of the instance, also invoking virtual getters. If an object has child objects or if options.clone===true, the object will be a copy. Otherwise, it will reference instance.dataValues.

    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

    Returns TModelAttributes

  • Type Parameters

    • K extends keyof Model<TModelAttributes, TCreationAttributes>

    Parameters

    Returns Model<TModelAttributes, TCreationAttributes>[K]

  • Parameters

    Returns unknown

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

  • Check whether the mode has any hooks of this type

    Type Parameters

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

    Parameters

    • hookType: K

    Returns boolean

  • Type Parameters

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

    Parameters

    • hookType: K

    Returns boolean

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

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

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

  • Remove hook from the model

    Type Parameters

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

    Parameters

    • hookType: K
    • name: string

    Returns Model<TModelAttributes, TCreationAttributes>

  • Parameters

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

    Returns Promise<void>

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

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

  • 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

  • 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

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

  • Private

    Parameters

    • attributes: string[]

    Returns string[]

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

  • 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

  • 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

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

  • 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

  • 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

  • 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

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

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

  • Builds a new model instance and persists it. Equivalent to calling build then save.

    Type Parameters

    Parameters

    Returns 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 or with affected count if options.returning is true, whenever supported by dialect

    Since

    4.36.0

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

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

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

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

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

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

  • 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 or with affected count if options.returning is true, whenever supported by dialect

    Type Parameters

    • M extends Model<any, any, M>

    Parameters

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

  • Type Parameters

    • M extends Model<any, any, M>

    Parameters

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

  • Refreshes the Model's attribute definition.

    Returns void

  • Remove attribute from model definition. Only use if you know what you're doing.

    Parameters

    • attribute: string

    Returns void

  • Remove hook from the model

    Type Parameters

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

    Parameters

    Returns HooksCtor<H>

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