Guides Reference Source
public class | source

Model

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

Model instances operate with the concept of a dataValues property, which stores the actual values represented by the instance. By default, the values from dataValues can also be accessed directly from the Instance, that is:

instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')

However, if getters and/or setters are defined for field they will be invoked, instead of returning the value from dataValues. Accessing properties directly or using get is preferred for regular use, getDataValue should only be used for custom getters.

See:

Static Method Summary

Static Public Methods
public static

addScope(name: string, scope: object | Function, options: object)

Add a new scope to the model.

public static

async aggregate(attribute: string, aggregateFunction: string, options: object): Promise<DataTypes|object>

Run an aggregation method on the specified field

public static

belongsTo(target: Model, options: object): BelongsTo

Creates an association between this (the source) and the provided target.

public static

belongsToMany(target: Model, options: object): BelongsToMany

Create an N:M association with a join table.

public static

build(values: object | Array, options: object): Model | Array<Model>

Builds a new model instance.

public static

async bulkCreate(records: Array, options: object): Promise<Array<Model>>

Create and insert multiple instances in bulk.

public static

async count(options: object): Promise<number>

Count the number of records matching the provided where clause.

public static

async create(values: object, options: object): Promise<Model>

Builds a new model instance and calls save on it.

public static

async decrement(fields: string | Array | object, options: object): Promise<Model[], ?number>

Decrement the value of one or more columns.

since 4.36.0
public static

async describe(schema: string, options: object): Promise

Run a describe query on the table.

public static

async destroy(options: object): Promise<number>

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

public static

async drop(options: object): Promise

Drop the table represented by this Model

public static

async findAll(options: object): Promise<Array<Model>>

Search for multiple instances.

public static

async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}>

Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query.

public static

async findByPk(param: number | bigint | string | Buffer, options: object): Promise<Model>

Search for a single instance by its primary key._

public static

A more performant findOrCreate that may not work under a transaction (working in postgres) Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again

public static

async findOne(options: object): Promise<Model|null>

Search for a single instance.

public static

async findOrBuild(options: object): Promise<Model, boolean>

Find a row that matches the query, or build (but don't save) the row if none is found. The successful result of the promise will be (instance, built)

public static

async findOrCreate(options: object): Promise<Model, boolean>

Find a row that matches the query, or build and save the row if none is found The successful result of the promise will be (instance, created)

public static

Returns the attributes of the model.

public static

Get the table name of the model, taking schema into account.

public static

hasMany(target: Model, options: object): HasMany

Creates a 1:m association between this (the source) and the provided target.

public static

hasOne(target: Model, options: object): HasOne

Creates an association between this (the source) and the provided target.

public static

async increment(fields: string | Array | object, options: object): Promise<Model[], ?number>

Increment the value of one or more columns.

public static

init(attributes: object, options: object): Model

Initialize a model, representing a table in the DB, with attributes and options.

public static

async max(field: string, options: object): Promise<*>

Find the maximum value of field

public static

async min(field: string, options: object): Promise<*>

Find the minimum value of field

public static

removeAttribute(attribute: string)

Remove attribute from model definition

public static

async restore(options: object): Promise

Restore multiple instances if paranoid is enabled.

public static

schema(schema: string, options: object): Model

Apply a schema to this model.

public static

scope(option: Array | object | string): Model

Apply a scope created in define to the model.

public static

async sum(field: string, options: object): Promise<number>

Find the sum of field

public static

async sync(options: object): Promise<Model>

Sync this Model to the DB, that is create the table.

public static

async truncate(options: object): Promise

Truncate all instances of the model.

public static

Get un-scoped model

public static

async update(values: object, options: object): Promise<Array<number, number>>

Update multiple instances that match the where options.

public static

async upsert(values: object, options: object): Promise<Array<Model, boolean|null>>

Insert or update a single row.

Constructor Summary

Public Constructor
public

constructor(values: object, options: object)

Builds a new model instance.

Member Summary

Public Members
public

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

public get

A reference to the sequelize instance

Method Summary

Public Methods
public

changed(key: string, value: any): boolean | Array

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.

public

async decrement(fields: string | Array | object, options: object): Promise

Decrement the value of one or more columns.

public

async destroy(options: object): Promise

Destroy the row corresponding to this instance.

public

equals(other: Model): boolean

Check whether this and other Instance refer to the same row

public

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

public

get(key: string, options: object): object | any

If no key is given, returns all values of the instance, also invoking virtual getters.

public

getDataValue(key: string): any

Get the value of the underlying data value

public

async increment(fields: string | Array | object, options: object): Promise<Model>

Increment the value of one or more columns.

since 4.0.0
public

Helper method to determine if a instance is "soft deleted".

public

previous(key: string): any | Array<any>

Returns the previous value for key from _previousDataValues.

public

async reload(options: object): Promise<Model>

Refresh the current instance in-place, i.e.

public

async restore(options: object): Promise

Restore the row corresponding to this instance.

public

async save(options: object): Promise<Model>

Validates this instance, and if the validation passes, persists it to the database.

public

set(key: string | object, value: any, options: object): Model

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

public

setDataValue(key: string, value: any)

Update the underlying data value

public

Convert the instance to a JSON representation.

public

async update(values: object, options: object): Promise<Model>

This is the same as calling set and then calling save but it only saves the exact values passed to it, making it more atomic and safer.

public

async validate(options: object): Promise

Validate the attributes of this instance according to validation rules set in the model definition.

public

where(checkVersion: boolean): object

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

Static Public Methods

public static addScope(name: string, scope: object | Function, options: object) source

Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined.

By default this will throw an error if a scope with that name already exists. Pass override: true in the options object to silence this error.

Params:

NameTypeAttributeDescription
name string

The name of the scope. Use defaultScope to override the default scope

scope object | Function

scope or options

options object
  • optional

scope options

options.override boolean
  • optional
  • default: false

override old scope if already defined

public static async aggregate(attribute: string, aggregateFunction: string, options: object): Promise<DataTypes|object> source

Run an aggregation method on the specified field

Params:

NameTypeAttributeDescription
attribute string

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

aggregateFunction string

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

options object
  • optional

Query options. See sequelize.query for full options

options.where object
  • optional

A hash of search attributes.

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.dataType DataTypes | string
  • optional

The type of the result. If field is a field in this Model, the default will be the type of that field, otherwise defaults to float.

options.distinct boolean
  • optional

Applies DISTINCT to the field being aggregated over

options.transaction Transaction
  • optional

Transaction to run query under

options.plain boolean
  • optional

When true, the first returned value of aggregateFunction is cast to dataType and returned. If additional attributes are specified, along with group clauses, set plain to false to return all values of all returned rows. Defaults to true

Return:

Promise<DataTypes|object>

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

public static belongsTo(target: Model, options: object): BelongsTo source

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

Params:

NameTypeAttributeDescription
target Model

The target model

options object
  • optional

belongsTo association options

options.hooks boolean
  • optional
  • default: false

Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks

options.as string
  • optional

The alias of this model, in singular form. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target

options.foreignKey string | object
  • optional

The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target

options.targetKey string
  • optional

The name of the attribute to use as the key for the association in the target table. Defaults to the primary key of the target table

options.onDelete string
  • optional
  • default: 'SET NULL|NO ACTION'

SET NULL if foreignKey allows nulls, NO ACTION if otherwise

options.onUpdate string
  • optional
  • default: 'CASCADE'

Sets 'ON UPDATE'

options.constraints boolean
  • optional
  • default: true

Should on update and on delete constraints be enabled on the foreign key.

Return:

BelongsTo

Example:

Profile.belongsTo(User) // This will add userId to the profile table

public static belongsToMany(target: Model, options: object): BelongsToMany source

Create an N:M association with a join table. Defining through is required.

Params:

NameTypeAttributeDescription
target Model

Target model

options object

belongsToMany association options

options.hooks boolean
  • optional
  • default: false

Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks

options.through Model | string | object

The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.

options.through.model Model
  • optional

The model used to join both sides of the N:M association.

options.through.scope object
  • optional

A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model)

options.through.unique boolean
  • optional
  • default: true

If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes)

options.through.paranoid boolean
  • optional
  • default: false

If true the generated join table will be paranoid

options.as string | object
  • optional

The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with plural and singular keys. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target

options.foreignKey string | object
  • optional

The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of source + primary key of source

options.otherKey string | object
  • optional

The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target

options.scope object
  • optional

A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)

options.timestamps boolean
  • optional
  • default: sequelize.options.timestamps

Should the join model have timestamps

options.onDelete string
  • optional
  • default: 'SET NULL|CASCADE'

Cascade if this is a n:m, and set null if it is a 1:m

options.onUpdate string
  • optional
  • default: 'CASCADE'

Sets ON UPDATE

options.constraints boolean
  • optional
  • default: true

Should on update and on delete constraints be enabled on the foreign key.

Return:

BelongsToMany

Example:

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

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

public static build(values: object | Array, options: object): Model | Array<Model> source

Builds a new model instance.

Params:

NameTypeAttributeDescription
values object | Array

An object of key value pairs or an array of such. If an array, the function will return an array of instances.

options object
  • optional

Instance build options

options.raw boolean
  • optional
  • default: false

If set to true, values will ignore field and virtual setters.

options.isNewRecord boolean
  • optional
  • default: true

Is this new record

options.include Array
  • optional

an array of include options - Used to build prefetched/included model instances. See set

Return:

Model | Array<Model>

public static async bulkCreate(records: Array, options: object): Promise<Array<Model>> source

Create and insert multiple instances in bulk.

The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. 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 Instances for the newly created values, you will need to query for them again.

If validation fails, the promise is rejected with an array-like AggregateError

Params:

NameTypeAttributeDescription
records Array

List of objects (key/value pairs) to create instances from

options object
  • optional

Bulk create options

options.fields Array
  • optional

Fields to insert (defaults to all fields)

options.validate boolean
  • optional
  • default: false

Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation

options.hooks boolean
  • optional
  • default: true

Run before / after bulk create hooks?

options.individualHooks boolean
  • optional
  • default: false

Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.

options.ignoreDuplicates boolean
  • optional
  • default: false

Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5)

options.updateOnDuplicate Array
  • optional

Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5).

options.conflictAttributes Array
  • optional

Optional override for the conflict fields in the ON CONFLICT part of the query. Only supported in Postgres >= 9.5 and SQLite >= 3.24.0

options.transaction Transaction
  • optional

Transaction to run query under

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.returning boolean | Array
  • optional
  • default: false

If true, append RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only)

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise<Array<Model>>

public static async count(options: object): Promise<number> source

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.

Params:

NameTypeAttributeDescription
options object
  • optional

options

options.where object
  • optional

A hash of search attributes.

options.include object
  • optional

Include options. See find for details

options.paranoid boolean
  • optional
  • default: true

Set true to count only non-deleted records. Can be used on models with paranoid enabled

options.distinct boolean
  • optional

Apply COUNT(DISTINCT(col)) on primary key or on options.col.

options.col string
  • optional

Column on which COUNT() should be applied

options.attributes Array
  • optional

Used in conjunction with group

options.group Array
  • optional

For creating complex counts. Will return multiple rows as needed.

options.transaction Transaction
  • optional

Transaction to run query under

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise<number>

public static async create(values: object, options: object): Promise<Model> source

Builds a new model instance and calls save on it.

Params:

NameTypeAttributeDescription
values object

Hash of data values to create new record with

options object
  • optional

Build and query options

options.raw boolean
  • optional
  • default: false

If set to true, values will ignore field and virtual setters.

options.isNewRecord boolean
  • optional
  • default: true

Is this new record

options.include Array
  • optional

An array of include options - Used to build prefetched/included model instances. See set

options.fields string[]
  • optional

An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.

options.silent boolean
  • optional
  • default: false

If true, the updatedAt timestamp will not be updated.

options.validate boolean
  • optional
  • default: true

If false, validations won't be run.

options.hooks boolean
  • optional
  • default: true

Run before and after create / update + validate hooks

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

options.returning boolean | Array
  • optional
  • default: true

Appends RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only)

Return:

Promise<Model>

See:

public static async decrement(fields: string | Array | object, options: object): Promise<Model[], ?number> since 4.36.0 source

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 sql SET column = column - X WHERE foo = 'bar' query. To get the correct value after a decrement into the Instance you should do a reload.

Params:

NameTypeAttributeDescription
fields string | Array | object

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.

options object

decrement options, similar to increment

Return:

Promise<Model[], ?number>

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

Example:

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

See:

public static async describe(schema: string, options: object): Promise source

Run a describe query on the table.

Params:

NameTypeAttributeDescription
schema string
  • optional

schema name to search table in

options object
  • optional

query options

Return:

Promise

hash of attributes and their types

public static async destroy(options: object): Promise<number> source

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

Params:

NameTypeAttributeDescription
options object

destroy options

options.where object
  • optional

Filter the destroy

options.hooks boolean
  • optional
  • default: true

Run before / after bulk destroy hooks?

options.individualHooks boolean
  • optional
  • default: false

If set to true, destroy will SELECT all records matching the where parameter and will execute before / after destroy hooks on each row

options.limit number
  • optional

How many rows to delete

options.force boolean
  • optional
  • default: false

Delete instead of setting deletedAt to current timestamp (only applicable if paranoid is enabled)

options.truncate boolean
  • optional
  • default: false

If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored

options.cascade boolean
  • optional
  • default: false

Only used in conjunction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.

options.restartIdentity boolean
  • optional
  • default: false

Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table.

options.transaction Transaction
  • optional

Transaction to run query under

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

Return:

Promise<number>

The number of destroyed rows

public static async drop(options: object): Promise source

Drop the table represented by this Model

Params:

NameTypeAttributeDescription
options object
  • optional

drop options

options.cascade boolean
  • optional
  • default: false

Also drop all objects depending on this table, such as views. Only works in postgres

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

Return:

Promise

public static async findAll(options: object): Promise<Array<Model>> source

Search for multiple instances.

Params:

NameTypeAttributeDescription
options object
  • optional

A hash of options to describe the scope of the search

options.where object
  • optional

A hash of attributes to describe your search. See above for examples.

options.attributes Array<string> | object
  • optional

A list of the attributes that you want to select, or an object with include and exclude keys. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the returned instance

options.attributes.include Array<string>
  • optional

Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. { attributes: { include: [[sequelize.fn('COUNT', sequelize.col('id')), 'total']] }

options.attributes.exclude Array<string>
  • optional

Select all the attributes of the model, except some few. Useful for security purposes e.g. { attributes: { exclude: ['password'] } }

options.paranoid boolean
  • optional
  • default: true

If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if options.paranoid is true for the model.

options.include Array<object|Model|string>
  • optional

A list of associations to eagerly load using a left join. Supported is either { include: [ Model1, Model2, ...]} or { include: [{ model: Model1, as: 'Alias' }]} or { include: ['Alias']}. If your association are set up with an as (eg. X.hasMany(Y, { as: 'Z' }, you need to specify Z in the as attribute when eager loading Y).

options.include[].model Model
  • optional

The model you want to eagerly load

options.include[].as string
  • optional

The alias of the relation, in case the model you want to eagerly load is aliased. For hasOne / belongsTo, this should be the singular name, and for hasMany, it should be the plural

options.include[].association Association
  • optional

The association you want to eagerly load. (This can be used instead of providing a model/as pair)

options.include[].where object
  • optional

Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set required: false

options.include[].or boolean
  • optional
  • default: false

Whether to bind the ON and WHERE clause together by OR instead of AND.

options.include[].on object
  • optional

Supply your own ON condition for the join.

options.include[].attributes Array<string>
  • optional

A list of attributes to select from the child model

options.include[].required boolean
  • optional

If true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if include.where is set, false otherwise.

options.include[].right boolean
  • optional

If true, converts to a right join if dialect support it. Ignored if include.required is true.

options.include[].separate boolean
  • optional

If true, runs a separate query to fetch the associated instances, only supported for hasMany associations

options.include[].limit number
  • optional

Limit the joined rows, only supported with include.separate=true

options.include[].through.as string
  • optional

The alias for the join model, in case you want to give it a different name than the default one.

options.include[].through.paranoid boolean
  • optional

If true, only non-deleted records will be returned from the join table. If false, both deleted and non-deleted records will be returned. Only applies if through model is paranoid.

options.include[].through.where object
  • optional

Filter on the join model for belongsToMany relations

options.include[].through.attributes Array
  • optional

A list of attributes to select from the join model for belongsToMany relations

options.include[].include Array<object|Model|string>
  • optional

Load further nested related models

options.include[].duplicating boolean
  • optional

Mark the include as duplicating, will prevent a subquery from being used.

options.order Array | fn | col | literal
  • optional

Specifies an ordering. Using an array, you can provide several columns / 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. For example: order: [['name', 'DESC']]. In this way the column will be escaped, but the direction will not.

options.limit number
  • optional

Limit for result

options.offset number
  • optional

Offset for result

options.transaction Transaction
  • optional

Transaction to run query under

options.lock string | object
  • optional

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.

options.skipLocked boolean
  • optional

Skip locked rows. Only supported in Postgres.

options.raw boolean
  • optional

Return raw result. See sequelize.query for more information.

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.having object
  • optional

Having options

options.searchPath string
  • optional
  • default: DEFAULT

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

options.rejectOnEmpty boolean | Error
  • optional
  • default: false

Throws an error when no records found

options.dotNotation boolean
  • optional

Allows including tables having the same attribute/column names - which have a dot in them.

options.nest boolean
  • optional
  • default: false

If true, transforms objects with . separated property names into nested objects.

Return:

Promise<Array<Model>>

Example:

Simple search using AND and =
Model.findAll({
  where: {
    attr1: 42,
    attr2: 'cake'
  }
})

# WHERE attr1 = 42 AND attr2 = 'cake'
Using greater than, less than etc.
const {gt, lte, ne, in: opIn} = Sequelize.Op;

Model.findAll({
  where: {
    attr1: {
      [gt]: 50
    },
    attr2: {
      [lte]: 45
    },
    attr3: {
      [opIn]: [1,2,3]
    },
    attr4: {
      [ne]: 5
    }
  }
})

# WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
Queries using OR
const {or, and, gt, lt} = Sequelize.Op;

Model.findAll({
  where: {
    name: 'a project',
    [or]: [
      {id: [1, 2, 3]},
      {
        [and]: [
          {id: {[gt]: 10}},
          {id: {[lt]: 100}}
        ]
      }
    ]
  }
});

# WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));

See:

  • Operators for possible operators __Alias__: _all_ The promise is resolved with an array of Model instances if the query succeeds._
  • Sequelize#query

public static async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}> source

Find 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 paging

Params:

NameTypeAttributeDescription
options object
  • optional

See findAll options

Return:

Promise<{count: number|number[], rows: Model[]}>

Example:

const result = await Model.findAndCountAll({
  where: ...,
  limit: 12,
  offset: 12
});

# 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

See:

public static async findByPk(param: number | bigint | string | Buffer, options: object): Promise<Model> source

Search for a single instance by its primary key._

Params:

NameTypeAttributeDescription
param number | bigint | string | Buffer

The value of the desired instance's primary key.

options object
  • optional

find options

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise<Model>

See:

  • Model.findAll for a full explanation of options, Note that options.where is not supported.

public static async findCreateFind(options: object): Promise<Model, boolean> source

A more performant findOrCreate that may not work under a transaction (working in postgres) Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again

Params:

NameTypeAttributeDescription
options object

find options

options.where object

A hash of search attributes. If where is a plain object it will be appended with defaults to build a new instance.

options.defaults object
  • optional

Default values to use if creating a new instance

Return:

Promise<Model, boolean>

See:

public static async findOne(options: object): Promise<Model|null> source

Search for a single instance. Returns the first instance found, or null if none can be found.

Params:

NameTypeAttributeDescription
options object
  • optional

A hash of options to describe the scope of the search

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise<Model|null>

See:

public static async findOrBuild(options: object): Promise<Model, boolean> source

Find a row that matches the query, or build (but don't save) the row if none is found. The successful result of the promise will be (instance, built)

Params:

NameTypeAttributeDescription
options object

find options

options.where object

A hash of search attributes. If where is a plain object it will be appended with defaults to build a new instance.

options.defaults object
  • optional

Default values to use if building a new instance

options.transaction object
  • optional

Transaction to run query under

Return:

Promise<Model, boolean>

public static async findOrCreate(options: object): Promise<Model, boolean> source

Find a row that matches the query, or build and save the row if none is found The successful result of the promise will be (instance, created)

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 sequelize. TimeoutError will be thrown instead. If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.

Params:

NameTypeAttributeDescription
options object

find and create options

options.where object

where A hash of search attributes. If where is a plain object it will be appended with defaults to build a new instance.

options.defaults object
  • optional

Default values to use if creating a new instance

options.transaction Transaction
  • optional

Transaction to run query under

Return:

Promise<Model, boolean>

See:

public static getAttributes(): object | any source

Returns the attributes of the model.

Return:

object | any

public static getTableName(): string | object source

Get the table name of the model, taking schema into account. The method will return The name as a string if the model has no schema, or an object with tableName, schema and delimiter properties.

Return:

string | object

public static hasMany(target: Model, options: object): HasMany source

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

Params:

NameTypeAttributeDescription
target Model

Target model

options object
  • optional

hasMany association options

options.hooks boolean
  • optional
  • default: false

Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks

options.as string | object
  • optional

The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with plural and singular keys. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target

options.foreignKey string | object
  • optional

The name of the foreign key in the target table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of source + primary key of source

options.sourceKey string
  • optional

The name of the field to use as the key for the association in the source table. Defaults to the primary key of the source table

options.scope object
  • optional

A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)

options.onDelete string
  • optional
  • default: 'SET NULL|CASCADE'

SET NULL if foreignKey allows nulls, CASCADE if otherwise

options.onUpdate string
  • optional
  • default: 'CASCADE'

Set ON UPDATE

options.constraints boolean
  • optional
  • default: true

Should on update and on delete constraints be enabled on the foreign key.

Return:

HasMany

Example:

User.hasMany(Profile) // This will add userId to the profile table

public static hasOne(target: Model, options: object): HasOne source

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

Params:

NameTypeAttributeDescription
target Model

Target model

options object
  • optional

hasOne association options

options.hooks boolean
  • optional
  • default: false

Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks

options.as string
  • optional

The alias of this model, in singular form. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target

options.foreignKey string | object
  • optional

The name of the foreign key attribute in the target model or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of source + primary key of source

options.sourceKey string
  • optional

The name of the attribute to use as the key for the association in the source table. Defaults to the primary key of the source table

options.onDelete string
  • optional
  • default: 'SET NULL|CASCADE'

SET NULL if foreignKey allows nulls, CASCADE if otherwise

options.onUpdate string
  • optional
  • default: 'CASCADE'

Sets 'ON UPDATE'

options.constraints boolean
  • optional
  • default: true

Should on update and on delete constraints be enabled on the foreign key.

options.uniqueKey string
  • optional

The custom name for unique constraint.

Return:

HasOne

Example:

User.hasOne(Profile) // This will add userId to the profile table

public static async increment(fields: string | Array | object, options: object): Promise<Model[], ?number> source

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 WHERE foo = 'bar' query. To get the correct value after an increment into the Instance you should do a reload.

Params:

NameTypeAttributeDescription
fields string | Array | object

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.

options object

increment options

options.where object

conditions hash

options.by number
  • optional
  • default: 1

The number to increment by

options.silent boolean
  • optional
  • default: false

If true, the updatedAt timestamp will not be updated.

options.logging Function
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise<Model[], ?number>

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

Example:

increment number by 1
Model.increment('number', { where: { foo: 'bar' });
increment number and count by 2
Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
increment answer by 42, and decrement tries by 1
// `by` is ignored, as each column has its own value
Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });

See:

public static init(attributes: object, options: object): Model source

Initialize a model, representing a table in the DB, with attributes and options.

The table columns are defined by the hash that is given as the first argument. Each attribute of the hash represents a column.

Params:

NameTypeAttributeDescription
attributes object

An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below:

attributes.column string | DataTypes | object

The description of a database column

attributes.column.type string | DataTypes

A string or a data type

attributes.column.allowNull boolean
  • optional
  • default: true

If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved.

attributes.column.defaultValue any
  • optional
  • default: null

A literal default value, a JavaScript function, or an SQL function (see sequelize.fn)

attributes.column.unique string | boolean
  • optional
  • default: false

If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index

attributes.column.primaryKey boolean
  • optional
  • default: false

If true, this attribute will be marked as primary key

attributes.column.field string
  • optional
  • default: null

If set, sequelize will map the attribute name to a different name in the database

attributes.column.autoIncrement boolean
  • optional
  • default: false

If true, this column will be set to auto increment

attributes.column.autoIncrementIdentity boolean
  • optional
  • default: false

If true, combined with autoIncrement=true, will use Postgres GENERATED BY DEFAULT AS IDENTITY instead of SERIAL. Postgres 10+ only.

attributes.column.comment string
  • optional
  • default: null

Comment for this column

attributes.column.references string | Model
  • optional
  • default: null

An object with reference configurations

attributes.column.references.model string | Model
  • optional

If this column references another table, provide it here as a Model, or a string

attributes.column.references.key string
  • optional
  • default: 'id'

The column of the foreign table that this column references

attributes.column.onUpdate string
  • optional

What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION

attributes.column.onDelete string
  • optional

What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION

attributes.column.get Function
  • optional

Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values.

attributes.column.set Function
  • optional

Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values.

attributes.column.validate object
  • optional

An object of validations to execute for this column every time the model is saved. Can be either the name of a validation provided by validator.js, a validation function provided by extending validator.js (see the DAOValidator property for more details), or a custom validation function. Custom validation functions are called with the value of the field and the instance itself as the this binding, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation; if it is async, the callback should be called with the error text.

options object

These options are merged with the default define options provided to the Sequelize constructor

options.sequelize object

Define the sequelize instance to attach to the new Model. Throw error if none is provided.

options.modelName string
  • optional

Set name of the model. By default its same as Class name.

options.defaultScope object
  • optional
  • default: {}

Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll

options.scopes object
  • optional

More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how scopes are defined, and what you can do with them

options.omitNull boolean
  • optional

Don't persist null values. This means that all columns with null values will not be saved

options.timestamps boolean
  • optional
  • default: true

Adds createdAt and updatedAt timestamps to the model.

options.paranoid boolean
  • optional
  • default: false

Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs timestamps=true to work

options.underscored boolean
  • optional
  • default: false

Add underscored field to all attributes, this covers user defined attributes, timestamps and foreign keys. Will not affect attributes with explicitly set field option

options.freezeTableName boolean
  • optional
  • default: false

If freezeTableName is true, sequelize will not try to alter the model name to get the table name. Otherwise, the model name will be pluralized

options.name object
  • optional

An object with two attributes, singular and plural, which are used when this model is associated to others.

options.name.singular string
  • optional
  • default: Utils.singularize(modelName)

Singular name for model

options.name.plural string
  • optional
  • default: Utils.pluralize(modelName)

Plural name for model

options.indexes Array<object>
  • optional

indexes definitions

options.indexes[].name string
  • optional

The name of the index. Defaults to model name + _ + fields concatenated

options.indexes[].type string
  • optional

Index type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL

options.indexes[].using string
  • optional

The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN.

options.indexes[].operator string
  • optional

Specify index operator.

options.indexes[].unique boolean
  • optional
  • default: false

Should the index by unique? Can also be triggered by setting type to UNIQUE

options.indexes[].concurrently boolean
  • optional
  • default: false

PostgresSQL will build the index without taking any write locks. Postgres only

options.indexes[].fields Array<string|object>
  • optional

An array of the fields to index. Each field can either be a string containing the name of the field, a sequelize object (e.g sequelize.fn), or an object with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the direction the column should be sorted in), collate (the collation (sort order) for the column)

options.createdAt string | boolean
  • optional

Override the name of the createdAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.

options.updatedAt string | boolean
  • optional

Override the name of the updatedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.

options.deletedAt string | boolean
  • optional

Override the name of the deletedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.

options.tableName string
  • optional

Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim

options.schema string
  • optional
  • default: 'public'

schema

options.engine string
  • optional

Specify engine for model's table

options.charset string
  • optional

Specify charset for model's table

options.comment string
  • optional

Specify comment for model's table

options.collate string
  • optional

Specify collation for model's table

options.initialAutoIncrement string
  • optional

Set the initial AUTO_INCREMENT value for the table in MySQL.

options.hooks object
  • optional

An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, beforeSave, afterDestroy, afterUpdate, afterBulkCreate, afterSave, afterBulkDestroy and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.

options.validate object
  • optional

An object of model wide validations. Validations have access to all model values via this. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error.

options.whereMergeStrategy 'and' | 'overwrite'
  • optional

Specify the scopes merging strategy (default 'overwrite'). 'and' strategy will merge where properties of scopes together by adding Op.and at the top-most level. 'overwrite' strategy will overwrite similar attributes using the lastly defined one.

Return:

Model

Example:

Project.init({
  columnA: {
    type: Sequelize.BOOLEAN,
    validate: {
      is: ['[a-z]','i'],        // will only allow letters
      max: 23,                  // only allow values <= 23
      isIn: {
        args: [['en', 'zh']],
        msg: "Must be English or Chinese"
      }
    },
    field: 'column_a'
    // Other attributes here
  },
  columnB: Sequelize.STRING,
  columnC: 'MY VERY OWN COLUMN TYPE'
}, {sequelize})

sequelize.models.modelName // The model will now be available in models under the class name

See:

public static async max(field: string, options: object): Promise<*> source

Find the maximum value of field

Params:

NameTypeAttributeDescription
field string

attribute / field name

options object
  • optional

See aggregate

Return:

Promise<*>

See:

public static async min(field: string, options: object): Promise<*> source

Find the minimum value of field

Params:

NameTypeAttributeDescription
field string

attribute / field name

options object
  • optional

See aggregate

Return:

Promise<*>

See:

public static removeAttribute(attribute: string) source

Remove attribute from model definition

Params:

NameTypeAttributeDescription
attribute string

name of attribute to remove

public static async restore(options: object): Promise source

Restore multiple instances if paranoid is enabled.

Params:

NameTypeAttributeDescription
options object

restore options

options.where object
  • optional

Filter the restore

options.hooks boolean
  • optional
  • default: true

Run before / after bulk restore hooks?

options.individualHooks boolean
  • optional
  • default: false

If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row

options.limit number
  • optional

How many rows to undelete (only for mysql)

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

Return:

Promise

public static schema(schema: string, options: object): Model source

Apply a schema to this model. 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.schema(schema, [options]).sync() for each model to ensure the models are created in the correct schema.

If a single default schema per model is needed, set the options.schema='schema' parameter during the define() call for the model.

Params:

NameTypeAttributeDescription
schema string

The name of the schema

options object
  • optional

schema options

options.schemaDelimiter string
  • optional
  • default: '.'

The character(s) that separates the schema name from the table name

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

Return:

Model

See:

public static scope(option: Array | object | string): Model source

Apply a scope created in define to the model.

Params:

NameTypeAttributeDescription
option Array | object | string
  • optional
  • nullable: true

The scope(s) 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.

Return:

Model

A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.

Example:

how to create scopes
const Model = sequelize.define('model', attributes, {
  defaultScope: {
    where: {
      username: 'dan'
    },
    limit: 12
  },
  scopes: {
    isALie: {
      where: {
        stuff: 'cake'
      }
    },
    complexFunction: function(email, accessLevel) {
      return {
        where: {
          email: {
            [Op.like]: email
          },
          access_level {
            [Op.gte]: accessLevel
          }
        }
      }
    }
  }
})

# As you have defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:

Model.findAll() // WHERE username = 'dan'
Model.findAll({ where: { age: { [Op.gt]: 12 } } }) // WHERE age > 12 AND username = 'dan'
To invoke scope functions you can do
Model.scope({ method: ['complexFunction', '[email protected]', 42]}).findAll()
// WHERE email like '[email protected]%' AND access_level >= 42

public static async sum(field: string, options: object): Promise<number> source

Find the sum of field

Params:

NameTypeAttributeDescription
field string

attribute / field name

options object
  • optional

See aggregate

Return:

Promise<number>

See:

public static async sync(options: object): Promise<Model> source

Sync this Model to the DB, that is create the table.

Params:

NameTypeAttributeDescription
options object
  • optional

sync options

Return:

Promise<Model>

See:

public static async truncate(options: object): Promise source

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

Params:

NameTypeAttributeDescription
options object
  • optional

The options passed to Model.destroy in addition to truncate

options.cascade boolean | Function
  • optional
  • default: false

Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.

options.restartIdentity boolean
  • optional
  • default: false

Automatically restart sequences owned by columns of the truncated table.

options.transaction Transaction
  • optional

Transaction to run query under

options.logging boolean | Function
  • optional

A function that logs sql queries, or false for no logging

options.benchmark boolean
  • optional
  • default: false

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

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise

See:

public static unscoped(): Model source

Get un-scoped model

Return:

Model

public static async update(values: object, options: object): Promise<Array<number, number>> source

Update multiple instances that match the where options.

Params:

NameTypeAttributeDescription
values object

hash of values to update

options object

update options

options.where object

Options to describe the scope of the search.

options.paranoid boolean
  • optional
  • default: true

If true, only non-deleted records will be updated. If false, both deleted and non-deleted records will be updated. Only applies if options.paranoid is true for the model.

options.fields Array
  • optional

Fields to update (defaults to all fields)

options.validate boolean
  • optional
  • default: true

Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation

options.hooks boolean
  • optional
  • default: true

Run before / after bulk update hooks?

options.sideEffects boolean
  • optional
  • default: true

Whether or not to update the side effects of any virtual setters.

options.individualHooks boolean
  • optional
  • default: false

Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. A select is needed, because the row data needs to be passed to the hooks

options.returning boolean | Array
  • optional
  • default: false

If true, append RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only)

options.limit number
  • optional

How many rows to update (only for mysql and mariadb, implemented as TOP(n) for MSSQL; for sqlite it is supported only when rowid is present)

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.silent boolean
  • optional
  • default: false

If true, the updatedAt timestamp will not be updated.

Return:

Promise<Array<number, number>>

The promise returns an array with one or two elements. The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true).

public static async upsert(values: object, options: object): Promise<Array<Model, boolean|null>> source

Insert or update a single row. 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 with ON DUPLICATE KEY UPDATE`
  • PostgreSQL - Implemented with ON CONFLICT DO UPDATE. If update data contains PK field, then PK is selected as the default conflict key. Otherwise first unique constraint/index will be selected, which can satisfy conflict key requirements.
  • SQLite - Implemented with ON CONFLICT DO UPDATE
  • MSSQL - Implemented as a single query using MERGE and WHEN (NOT) MATCHED THEN

Note that Postgres/SQLite returns null for created, no matter if the row was created or updated

Params:

NameTypeAttributeDescription
values object

hash of values to upsert

options object
  • optional

upsert options

options.validate boolean
  • optional
  • default: true

Run validations before the row is inserted

options.fields Array
  • optional
  • default: Object.keys(this.attributes)

The fields to update if the record already exists. Defaults to all changed fields. If none of the specified fields are present on the provided values object, an insert will still be attempted, but duplicate key conflicts will be ignored.

options.hooks boolean
  • optional
  • default: true

Run before / after upsert hooks?

options.returning boolean
  • optional
  • default: true

If true, fetches back auto generated values

options.transaction Transaction
  • optional

Transaction to run query under

options.logging Function
  • optional
  • default: false

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

options.benchmark boolean
  • optional
  • default: false

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

options.searchPath string
  • optional
  • default: DEFAULT

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

options.conflictFields Array<string>
  • optional

Optional override for the conflict fields in the ON CONFLICT part of the query. Only supported in Postgres >= 9.5 and SQLite >= 3.24.0

Return:

Promise<Array<Model, boolean|null>>

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

Public Constructors

public constructor(values: object, options: object) source

Builds a new model instance.

Params:

NameTypeAttributeDescription
values object
  • optional
  • default: {}

an object of key value pairs

options object
  • optional

instance construction options

options.raw boolean
  • optional
  • default: false

If set to true, values will ignore field and virtual setters.

options.isNewRecord boolean
  • optional
  • default: true

Is this a new record

options.include Array
  • optional

an array of include options - Used to build prefetched/included model instances. See set

Public Members

public isNewRecord: boolean: * source

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

Properties:

NameTypeAttributeDescription
isNewRecord *

Return:

boolean

Return Properties:

NameTypeAttributeDescription
isNewRecord *

public get sequelize: Sequelize: * source

A reference to the sequelize instance

Properties:

NameTypeAttributeDescription
sequelize *

Return:

Sequelize

Return Properties:

NameTypeAttributeDescription
sequelize *

See:

Public Methods

public changed(key: string, value: any): boolean | Array source

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 without an argument and no keys have changed, it will return false.

Please note that this function will return false when a property from a nested (for example JSON) property was edited manually, you must call changed('key', true) manually in these cases. Writing an entirely new object (eg. deep cloned) will be detected.

Params:

NameTypeAttributeDescription
key string
  • optional

key to check or change status of

value any
  • optional

value to set

Return:

boolean | Array

Example:

```
const mdl = await MyModel.findOne();
mdl.myJsonField.a = 1;
console.log(mdl.changed()) => false
mdl.save(); // this will not save anything
mdl.changed('myJsonField', true);
console.log(mdl.changed()) => ['myJsonField']
mdl.save(); // will save
```

public async decrement(fields: string | Array | object, options: object): Promise source

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. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values.

Params:

NameTypeAttributeDescription
fields string | Array | object

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

options object
  • optional

decrement options

options.by number
  • optional
  • default: 1

The number to decrement by

options.silent boolean
  • optional
  • default: false

If true, the updatedAt timestamp will not be updated.

options.logging Function
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

options.returning boolean
  • optional
  • default: true

Append RETURNING * to get back auto generated values (Postgres only)

Return:

Promise

Example:

instance.decrement('number') // decrement number by 1

instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2

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

See:

public async destroy(options: object): Promise source

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

Params:

NameTypeAttributeDescription
options object
  • optional
  • default: {}

destroy options

options.force boolean
  • optional
  • default: false

If set to true, paranoid models will actually be deleted

options.logging Function
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

Return:

Promise

public equals(other: Model): boolean source

Check whether this and other Instance refer to the same row

Params:

NameTypeAttributeDescription
other Model

Other instance to compare against

Return:

boolean

public equalsOneOf(others: Array<Model>): boolean source

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

Params:

NameTypeAttributeDescription
others Array<Model>

An array of instances to check against

Return:

boolean

public get(key: string, options: object): object | any source

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.

Params:

NameTypeAttributeDescription
key string
  • optional

key to get value of

options object
  • optional

get options

options.plain boolean
  • optional
  • default: false

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

options.raw boolean
  • optional
  • default: false

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

Return:

object | any

public getDataValue(key: string): any source

Get the value of the underlying data value

Params:

NameTypeAttributeDescription
key string

key to look in instance data store

Return:

any

public async increment(fields: string | Array | object, options: object): Promise<Model> since 4.0.0 source

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. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values.

Params:

NameTypeAttributeDescription
fields string | Array | object

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.

options object
  • optional

options

options.by number
  • optional
  • default: 1

The number to increment by

options.silent boolean
  • optional
  • default: false

If true, the updatedAt timestamp will not be updated.

options.logging Function
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

options.returning boolean
  • optional
  • default: true

Append RETURNING * to get back auto generated values (Postgres only)

Return:

Promise<Model>

Example:

instance.increment('number') // increment number by 1

instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2

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

See:

public isSoftDeleted(): boolean source

Helper method to determine if a instance is "soft deleted". This is particularly useful if the implementer renamed the deletedAt attribute to something different. This method requires paranoid to be enabled.

Return:

boolean

public previous(key: string): any | Array<any> source

Returns the previous value for key from _previousDataValues.

If called without a key, returns the previous values for all values which have changed

Params:

NameTypeAttributeDescription
key string
  • optional

key to get previous value of

Return:

any | Array<any>

public async reload(options: object): Promise<Model> source

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

Params:

NameTypeAttributeDescription
options object
  • optional

Options that are passed on to Model.find

options.logging Function
  • optional
  • default: false

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

Return:

Promise<Model>

See:

public async restore(options: object): Promise source

Restore the row corresponding to this instance. Only available for paranoid models.

Params:

NameTypeAttributeDescription
options object
  • optional
  • default: {}

restore options

options.logging Function
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

Return:

Promise

public async save(options: object): Promise<Model> source

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

Params:

NameTypeAttributeDescription
options object
  • optional

save options

options.fields string[]
  • optional

An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.

options.silent boolean
  • optional
  • default: false

If true, the updatedAt timestamp will not be updated.

options.validate boolean
  • optional
  • default: true

If false, validations won't be run.

options.hooks boolean
  • optional
  • default: true

Run before and after create / update + validate hooks

options.logging Function
  • optional
  • default: false

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

options.transaction Transaction
  • optional

Transaction to run query under

options.searchPath string
  • optional
  • default: DEFAULT

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

options.returning boolean
  • optional

Append RETURNING * to get back auto generated values (Postgres only)

Return:

Promise<Model>

public set(key: string | object, value: any, options: object): Model source

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.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.

Params:

NameTypeAttributeDescription
key string | object

key to set, it can be string or object. When string it will set that key, for object it will loop over all object properties nd set them.

value any

value to set

options object
  • optional

set options

options.raw boolean
  • optional
  • default: false

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

options.reset boolean
  • optional
  • default: false

Clear all previously set data values

Return:

Model

See:

public setDataValue(key: string, value: any) source

Update the underlying data value

Params:

NameTypeAttributeDescription
key string

key to set in instance data store

value any

new value for given key

public toJSON(): object source

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.

Return:

object

See:

public async update(values: object, options: object): Promise<Model> source

This is the same as calling set and then calling save but it only saves the exact values passed to it, making it more atomic and safer.

Params:

NameTypeAttributeDescription
values object

See set

options object

See save

Return:

Promise<Model>

See:

public async validate(options: object): Promise source

Validate the attributes of this instance according to validation rules set in the model definition.

The promise fulfills if and only if validation successful; otherwise it rejects an Error instance containing { field name : [error msgs] } entries.

Params:

NameTypeAttributeDescription
options object
  • optional

Options that are passed to the validator

options.skip Array
  • optional

An array of strings. All properties that are in this array will not be validated

options.fields Array
  • optional

An array of strings. Only the properties that are in this array will be validated

options.hooks boolean
  • optional
  • default: true

Run before and after validate hooks

Return:

Promise

public where(checkVersion: boolean): object source

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

Params:

NameTypeAttributeDescription
checkVersion boolean
  • optional
  • default: false

include version attribute in where hash

Return:

object