sequelize
- Version 6.37.5
- Published
- 2.91 MB
- 16 dependencies
- MIT license
Install
npm i sequelize
yarn add sequelize
pnpm add sequelize
Overview
Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift and Snowflake’s Data Cloud. It features solid transaction support, relations, eager and lazy loading, read replication and more.
Index
Variables
Functions
Classes
Model
- addScope()
- afterBulkCreate()
- afterBulkDestroy()
- afterBulkSync()
- afterBulkUpdate()
- afterCreate()
- afterDestroy()
- afterFind()
- afterSave()
- afterSync()
- afterUpdate()
- afterValidate()
- aggregate()
- associations
- beforeBulkCreate()
- beforeBulkDestroy()
- beforeBulkSync()
- beforeBulkUpdate()
- beforeCount()
- beforeCreate()
- beforeDestroy()
- beforeFind()
- beforeFindAfterExpandIncludeAll()
- beforeFindAfterOptions()
- beforeSave()
- beforeSync()
- beforeUpdate()
- beforeValidate()
- belongsTo()
- belongsToMany()
- build()
- bulkBuild()
- bulkCreate()
- changed()
- count()
- create()
- dataValues
- decrement()
- describe()
- destroy()
- drop()
- equals()
- equalsOneOf()
- findAll()
- findAndCountAll()
- findByPk()
- findCreateFind()
- findOne()
- findOrBuild()
- findOrCreate()
- get()
- getAttributes()
- getDataValue()
- getTableName()
- hasMany()
- hasOne()
- increment()
- init()
- isNewRecord
- isSoftDeleted()
- max()
- min()
- options
- previous()
- primaryKeyAttribute
- primaryKeyAttributes
- rawAttributes
- reload()
- removeAttribute()
- restore()
- save()
- schema()
- scope()
- sequelize
- sequelize
- set()
- setAttributes()
- setDataValue()
- sum()
- sync()
- tableName
- toJSON()
- truncate()
- unscoped()
- update()
- upsert()
- validate()
- where()
QueryInterface
- addColumn()
- addConstraint()
- addIndex()
- bulkDelete()
- bulkInsert()
- bulkUpdate()
- changeColumn()
- commitTransaction()
- createDatabase()
- createFunction()
- createSchema()
- createTable()
- createTrigger()
- databaseVersion()
- deferConstraints()
- delete()
- describeTable()
- dropAllEnums()
- dropAllSchemas()
- dropAllTables()
- dropDatabase()
- dropFunction()
- dropSchema()
- dropTable()
- dropTrigger()
- getForeignKeyReferencesForTable()
- getForeignKeysForTables()
- increment()
- insert()
- nameIndexes()
- queryGenerator
- quoteIdentifier()
- quoteIdentifiers()
- quoteTable()
- rawSelect()
- removeColumn()
- removeConstraint()
- removeIndex()
- renameColumn()
- renameFunction()
- renameTable()
- renameTrigger()
- rollbackTransaction()
- select()
- sequelize
- setAutocommit()
- setIsolationLevel()
- showAllSchemas()
- showAllTables()
- showIndex()
- startTransaction()
- tableExists()
- update()
- upsert()
Sequelize
- afterBulkCreate()
- afterBulkDestroy()
- afterBulkSync()
- afterBulkUpdate()
- afterConnect()
- afterCreate()
- afterDefine()
- afterDestroy()
- afterDisconnect()
- afterFind()
- afterInit()
- afterPoolAcquire()
- afterSave()
- afterSync()
- afterUpdate()
- afterValidate()
- and
- and
- authenticate()
- beforeBulkCreate()
- beforeBulkDestroy()
- beforeBulkSync()
- beforeBulkUpdate()
- beforeConnect()
- beforeCreate()
- beforeDefine()
- beforeDestroy()
- beforeDisconnect()
- beforeFind()
- beforeFindAfterExpandIncludeAll()
- beforeFindAfterOptions()
- beforeInit()
- beforePoolAcquire()
- beforeSave()
- beforeSync()
- beforeUpdate()
- beforeValidate()
- cast
- cast
- close()
- col
- col
- config
- connectionManager
- createSchema()
- databaseVersion()
- define()
- drop()
- dropAllSchemas()
- dropSchema()
- escape()
- fn
- fn
- getDatabaseName()
- getDialect()
- getQueryInterface()
- isDefined()
- json
- json
- literal
- literal
- model()
- modelManager
- models
- or
- or
- query()
- random()
- Sequelize
- set()
- showAllSchemas()
- sync()
- transaction()
- truncate()
- useCLS()
- validate()
- where
- where
Interfaces
Options
- attributeBehavior
- clientMinMessages
- database
- define
- dialect
- dialectModule
- dialectModulePath
- dialectOptions
- hooks
- host
- isolationLevel
- logQueryParameters
- minifyAliases
- native
- omitNull
- operatorsAliases
- password
- pool
- port
- protocol
- query
- quoteIdentifiers
- replication
- retry
- schema
- set
- ssl
- standardConformingStrings
- storage
- sync
- timezone
- transactionType
- typeValidation
- username
WhereOperators
- [Op.adjacent]
- [Op.between]
- [Op.contained]
- [Op.contains]
- [Op.endsWith]
- [Op.eq]
- [Op.gt]
- [Op.gte]
- [Op.iLike]
- [Op.in]
- [Op.iRegexp]
- [Op.is]
- [Op.like]
- [Op.lt]
- [Op.lte]
- [Op.match]
- [Op.ne]
- [Op.noExtendLeft]
- [Op.noExtendRight]
- [Op.not]
- [Op.notBetween]
- [Op.notILike]
- [Op.notIn]
- [Op.notIRegexp]
- [Op.notLike]
- [Op.notRegexp]
- [Op.overlap]
- [Op.regexp]
- [Op.startsWith]
- [Op.strictLeft]
- [Op.strictRight]
- [Op.substring]
Enums
Type Aliases
- AddConstraintOptions
- AllowReadonlyArray
- Attributes
- AttributeType
- BelongsToCreateAssociationMixin
- BelongsToGetAssociationMixin
- BelongsToManyAddAssociationMixin
- BelongsToManyAddAssociationsMixin
- BelongsToManyCountAssociationsMixin
- BelongsToManyCreateAssociationMixin
- BelongsToManyGetAssociationsMixin
- BelongsToManyHasAssociationMixin
- BelongsToManyHasAssociationsMixin
- BelongsToManyRemoveAssociationMixin
- BelongsToManyRemoveAssociationsMixin
- BelongsToManySetAssociationsMixin
- BelongsToSetAssociationMixin
- BindOrReplacements
- BlobSize
- ColumnReference
- CountWithOptions
- CreationAttributes
- CreationOptional
- DataType
- DataTypeAbstract
- Dialect
- FieldMap
- FindAttributeOptions
- ForeignKey
- GroupOption
- HasManyAddAssociationMixin
- HasManyAddAssociationsMixin
- HasManyCountAssociationsMixin
- HasManyCreateAssociationMixin
- HasManyGetAssociationsMixin
- HasManyHasAssociationMixin
- HasManyHasAssociationsMixin
- HasManyRemoveAssociationMixin
- HasManyRemoveAssociationsMixin
- HasManySetAssociationsMixin
- HasOneCreateAssociationMixin
- HasOneGetAssociationMixin
- HasOneSetAssociationMixin
- Identifier
- Includeable
- IndexMethod
- IndexType
- InferAttributes
- InferCreationAttributes
- LogicType
- ModelAttributes
- ModelCtor
- ModelDefined
- ModelIndexesOptions
- ModelStatic
- ModelType
- NonAttribute
- Optional
- Order
- OrderItem
- ProjectionAlias
- Rangable
- Range
- RangeableDataType
- RetryOptions
- TableName
- TextLength
- WhereAttributeHash
- WhereAttributeHashValue
- WhereLeftOperand
- WhereOptions
- WhereValue
Namespaces
Variables
variable ABSTRACT
const ABSTRACT: AbstractDataTypeConstructor;
variable ARRAY
const ARRAY: ArrayDataTypeConstructor;
An array of
type
, e.g.DataTypes.ARRAY(DataTypes.DECIMAL)
. Only available in postgres.
variable BIGINT
const BIGINT: BigIntDataTypeConstructor;
A 64 bit integer.
Available properties:
UNSIGNED
,ZEROFILL
variable BLOB
const BLOB: BlobDataTypeConstructor;
Binary storage. Available lengths:
tiny
,medium
,long
variable BOOLEAN
const BOOLEAN: AbstractDataTypeConstructor;
A boolean / tinyint column, depending on dialect
variable CHAR
const CHAR: CharDataTypeConstructor;
A fixed length string. Default length 255
variable CIDR
const CIDR: AbstractDataTypeConstructor;
variable CITEXT
const CITEXT: AbstractDataTypeConstructor;
Case-insensitive text
variable DATE
const DATE: DateDataTypeConstructor;
A datetime column
variable DATEONLY
const DATEONLY: DateOnlyDataTypeConstructor;
A date only column
variable DECIMAL
const DECIMAL: DecimalDataTypeConstructor;
Decimal number. Accepts one or two arguments for precision
variable DOUBLE
const DOUBLE: DoubleDataTypeConstructor;
Floating point number (8-byte precision). Accepts one or two arguments for precision
variable ENUM
const ENUM: EnumDataTypeConstructor;
An enumeration.
DataTypes.ENUM('value', 'another value')
.
variable FLOAT
const FLOAT: FloatDataTypeConstructor;
Floating point number (4-byte precision). Accepts one or two arguments for precision
variable GEOGRAPHY
const GEOGRAPHY: GeographyDataTypeConstructor;
A geography datatype represents two dimensional spacial objects in an elliptic coord system.
variable GEOMETRY
const GEOMETRY: GeometryDataTypeConstructor;
A geometry datatype represents two dimensional spacial objects.
variable HSTORE
const HSTORE: AbstractDataTypeConstructor;
A key / value column. Only available in postgres.
variable INET
const INET: AbstractDataTypeConstructor;
variable INTEGER
const INTEGER: IntegerDataTypeConstructor;
A 32 bit integer.
variable JSON
const JSON: AbstractDataTypeConstructor;
A JSON string column. Only available in postgres.
variable JSONB
const JSONB: AbstractDataTypeConstructor;
A pre-processed JSON data column. Only available in postgres.
variable MACADDR
const MACADDR: AbstractDataTypeConstructor;
variable MEDIUMINT
const MEDIUMINT: MediumIntegerDataTypeConstructor;
A 24 bit integer.
variable NOW
const NOW: AbstractDataTypeConstructor;
A default value of the current timestamp
variable NUMBER
const NUMBER: NumberDataTypeConstructor;
variable Op
const Op: OpTypes;
variable RANGE
const RANGE: RangeDataTypeConstructor;
Range types are data types representing a range of values of some element type (called the range's subtype). Only available in postgres.
See [Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details
variable REAL
const REAL: RealDataTypeConstructor;
Floating point number (4-byte precision). Accepts one or two arguments for precision
variable SMALLINT
const SMALLINT: SmallIntegerDataTypeConstructor;
A 16 bit integer.
variable STRING
const STRING: StringDataTypeConstructor;
A variable length string. Default length 255
variable TEXT
const TEXT: TextDataTypeConstructor;
An (un)limited length text column. Available lengths:
tiny
,medium
,long
variable TIME
const TIME: AbstractDataTypeConstructor;
A time column
variable TINYINT
const TINYINT: TinyIntegerDataTypeConstructor;
A 8 bit integer.
variable TSVECTOR
const TSVECTOR: AbstractDataTypeConstructor;
Full text search vector. Only available in postgres.
variable UUID
const UUID: AbstractDataTypeConstructor;
A column storing a unique universal identifier. Use with
UUIDV1
orUUIDV4
for default values.
variable UUIDV1
const UUIDV1: AbstractDataTypeConstructor;
A default unique universal identifier generated following the UUID v1 standard
variable UUIDV4
const UUIDV4: AbstractDataTypeConstructor;
A default unique universal identifier generated following the UUID v4 standard
variable VIRTUAL
const VIRTUAL: VirtualDataTypeConstructor;
A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:
class User extends Model {}User.init({password_hash: DataTypes.STRING,password: {type: DataTypes.VIRTUAL,set (val) {this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validatedthis.setDataValue('password_hash', this.salt + val);},validate: {isLongEnough (val) {if (val.length < 7) {throw new Error("Please choose a longer password")}}}}}, { sequelize });VIRTUAL also takes a return type and dependency fields as arguments If a virtual attribute is present in
attributes
it will automatically pull in the extra fields as well. Return type is mostly useful for setups that rely on types like GraphQL.{active: {type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),get() {return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)}}}In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
Functions
function and
and: <T extends any[]>(...args: T) => { [Op.and]: T };
An AND query
Parameter args
Each argument will be joined by AND
function cast
cast: (val: unknown, type: string) => Cast;
Creates a object representing a call to the cast function.
Parameter val
The value to cast
Parameter type
The type to cast it to
function col
col: (col: string) => Col;
Creates a object representing a column in the DB. This is often useful in conjunction with
sequelize.fn
, since raw string arguments to fn will be escaped.Parameter col
The name of the column
function fn
fn: (fn: string, ...args: unknown[]) => Fn;
Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. If you want to refer to columns in your function, you should use
sequelize.col
, so that the columns are properly interpreted as columns and not a strings.Convert a user's username to upper case
instance.update({username: self.sequelize.fn('upper', self.sequelize.col('username'))})Parameter fn
The function you want to call
Parameter args
All further arguments will be passed as arguments to the function
function json
json: ( conditionsOrPath: string | object, value?: string | number | boolean) => Json;
Creates an object representing nested where conditions for postgres's json data-type.
Parameter conditionsOrPath
A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
Parameter value
An optional value to compare against. Produces a string of the form "<json path> = ''".
function literal
literal: (val: string) => Literal;
Creates a object representing a literal, i.e. something that will not be escaped.
Parameter val
function or
or: <T extends any[]>(...args: T) => { [Op.or]: T };
An OR query
Parameter args
Each argument will be joined by OR
function useInflection
useInflection: (inflection: Inflector) => void;
function where
where: { <Op extends keyof WhereOperators<any>>( leftOperand: WhereLeftOperand | Where, operator: Op, rightOperand: WhereOperators[Op] ): Where; <Op extends keyof WhereOperators<any>>( leftOperand: any, operator: string, rightOperand: any ): Where; (leftOperand: WhereLeftOperand, rightOperand: any): Where;};
A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g.
where: { name: 'Lily' }
) when you need to compare a column that the POJO syntax cannot represent.Parameter leftOperand
The left side of the comparison. - A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition. - A Literal (using Sequelize#literal) - A SQL Function (using Sequelize#fn) - A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
Parameter operator
The comparison operator to use. If unspecified, defaults to Op.eq.
Parameter rightOperand
The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.
Example 1
// Using an attribute as the left operand. // Equal to: WHERE first_name = 'Lily' where(User.rawAttributes.firstName, Op.eq, 'Lily');
Example 2
// Using a column name as the left operand. // Equal to: WHERE first_name = 'Lily' where(col('first_name'), Op.eq, 'Lily');
Example 3
// Using a SQL function on the left operand. // Equal to: WHERE LOWER(first_name) = 'lily' where(fn('LOWER', col('first_name')), Op.eq, 'lily');
Example 4
// Using raw SQL as the left operand. // Equal to: WHERE 'Lily' = 'Lily' where(literal(
'Lily'
), Op.eq, 'Lily');
Classes
class AccessDeniedError
class AccessDeniedError extends ConnectionError {}
Thrown when a connection to a database is refused due to insufficient privileges
constructor
constructor(parent: Error);
class AggregateError
class AggregateError extends BaseError {}
A wrapper for multiple Errors
Parameter errors
The aggregated errors that occurred
constructor
constructor(errors: (Error | AggregateError)[]);
property errors
readonly errors: (Error | AggregateError)[];
the aggregated errors that occurred
method toString
toString: () => string;
class Association
abstract class Association<S extends Model = Model, T extends Model = Model> {}
property as
as: string;
property associationType
associationType: string;
property foreignKey
foreignKey: string;
property identifier
identifier: string;
property isAliased
isAliased: boolean;
property isMultiAssociation
isMultiAssociation: boolean;
property isSelfAssociation
isSelfAssociation: boolean;
property isSingleAssociation
isSingleAssociation: boolean;
property source
source: ModelCtor<S>;
property target
target: ModelCtor<T>;
method inspect
inspect: () => string;
class AssociationError
class AssociationError extends BaseError {}
Thrown when an association is improperly constructed (see message for details)
constructor
constructor(message: string);
class AsyncQueueError
class AsyncQueueError extends BaseError {}
Thrown when a connection to a database is closed while an operation is in progress
constructor
constructor(message: string);
class BaseError
abstract class BaseError extends Error {}
The Base Error all Sequelize Errors inherit from.
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the base JS error object.
This means that errors can be accessed using
Sequelize.ValidationError
constructor
constructor(message?: string);
class BelongsTo
class BelongsTo< S extends Model = Model, T extends Model = Model> extends Association<S, T> {}
constructor
constructor( source: ModelCtor<S>, target: ModelCtor<T>, options: BelongsToOptions);
property accessors
accessors: SingleAssociationAccessors;
class BelongsToMany
class BelongsToMany< S extends Model = Model, T extends Model = Model> extends Association<S, T> {}
constructor
constructor( source: ModelCtor<S>, target: ModelCtor<T>, options: BelongsToManyOptions);
property accessors
accessors: MultiAssociationAccessors;
property otherKey
otherKey: string;
property sourceKey
sourceKey: string;
property targetKey
targetKey: string;
class BulkRecordError
class BulkRecordError extends BaseError {}
Thrown when bulk operation fails, it represent per record level error. Used with AggregateError
Parameter error
Error for a given record/instance
Parameter record
DAO instance that error belongs to
constructor
constructor(error: Error, record: Model<any, any>);
property errors
errors: Error;
property record
record: Model<any, any>;
class ConnectionAcquireTimeoutError
class ConnectionAcquireTimeoutError extends ConnectionError {}
Thrown when connection is not acquired due to timeout
constructor
constructor(parent: Error);
class ConnectionError
class ConnectionError extends BaseError {}
A base class for all connection related errors.
constructor
constructor(parent: Error);
property original
original: Error;
property parent
parent: Error;
The connection specific error which triggered this one
class ConnectionRefusedError
class ConnectionRefusedError extends ConnectionError {}
Thrown when a connection to a database is refused
constructor
constructor(parent: Error);
class ConnectionTimedOutError
class ConnectionTimedOutError extends ConnectionError {}
Thrown when a connection to a database times out
constructor
constructor(parent: Error);
class DatabaseError
class DatabaseError extends BaseError implements DatabaseErrorParent, CommonErrorProperties {}
A base class for all database related errors.
constructor
constructor(parent: DatabaseErrorParent, options?: ErrorOptions);
Parameter parent
The database specific error which triggered this one
Parameter options
property original
original: Error;
property parameters
parameters: {};
property parent
parent: Error;
property sql
sql: string;
class EagerLoadingError
class EagerLoadingError extends BaseError {}
Thrown when an include statement is improperly constructed (see message for details)
constructor
constructor(message: string);
class EmptyResultError
class EmptyResultError extends BaseError {}
Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
constructor
constructor(message: string);
class Error
abstract class BaseError extends Error {}
The Base Error all Sequelize Errors inherit from.
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the base JS error object.
This means that errors can be accessed using
Sequelize.ValidationError
constructor
constructor(message?: string);
class ExclusionConstraintError
class ExclusionConstraintError extends DatabaseError implements ExclusionConstraintErrorOptions {}
Thrown when an exclusion constraint is violated in the database
constructor
constructor( options: DatabaseErrorSubclassOptions & ExclusionConstraintErrorOptions);
property constraint
constraint: string;
property fields
fields: Record<string, string | number>;
property table
table: string;
class ForeignKeyConstraintError
class ForeignKeyConstraintError extends DatabaseError {}
Thrown when a foreign key constraint is violated in the database
class HasMany
class HasMany<S extends Model = Model, T extends Model = Model> extends Association< S, T> {}
constructor
constructor(source: ModelCtor<S>, target: ModelCtor<T>, options: HasManyOptions);
property accessors
accessors: MultiAssociationAccessors;
class HasOne
class HasOne<S extends Model = Model, T extends Model = Model> extends Association< S, T> {}
constructor
constructor(source: ModelCtor<S>, target: ModelCtor<T>, options: HasOneOptions);
property accessors
accessors: SingleAssociationAccessors;
class HostNotFoundError
class HostNotFoundError extends ConnectionError {}
Thrown when a connection to a database has a hostname that was not found
constructor
constructor(parent: Error);
class HostNotReachableError
class HostNotReachableError extends ConnectionError {}
Thrown when a connection to a database has a hostname that was not reachable
constructor
constructor(parent: Error);
class InstanceError
class InstanceError extends BaseError {}
Thrown when a some problem occurred with Instance methods (see message for details)
constructor
constructor(message: string);
class InvalidConnectionError
class InvalidConnectionError extends ConnectionError {}
Thrown when a connection to a database has invalid values for any of the connection parameters
constructor
constructor(parent: Error);
class Model
abstract class Model< TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes> extends Hooks< Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes> {}
constructor
constructor(values?: Optional<{}, never>, options?: BuildOptions);
Builds a new model instance.
Parameter values
an object of key value pairs
property associations
static readonly associations: { [key: string]: Association<Model<any, any>, Model<any, any>>;};
An object hash from alias to association object
property dataValues
dataValues: {};
Object that contains underlying model data
property isNewRecord
isNewRecord: boolean;
Returns true if this instance has not yet been persisted to the database
property options
static readonly options: InitOptions<Model<any, any>>;
The options that the model was initialized with
property primaryKeyAttribute
static readonly primaryKeyAttribute: string;
The name of the primary key attribute
property primaryKeyAttributes
static readonly primaryKeyAttributes: readonly string[];
The name of the primary key attributes
property rawAttributes
static readonly rawAttributes: { [attribute: string]: ModelAttributeColumnOptions<Model<any, any>>;};
The attributes of the model.
Deprecated
use Model.getAttributes for better typings.
property sequelize
static readonly sequelize?: Sequelize;
Reference to the sequelize instance the model was initialized with
property sequelize
sequelize: Sequelize;
A reference to the sequelize instance
property tableName
static readonly tableName: string;
The name of the database table
method addScope
static addScope: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, scope: FindOptions<Attributes<M>>, options?: AddScopeOptions ): void; <M extends Model<any, any>>( this: ModelStatic<M>, name: string, scope: (...args: readonly any[]) => FindOptions<Attributes<M>>, options?: AddScopeOptions ): void;};
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.
method afterBulkCreate
static afterBulkCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instances: readonly M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instances: readonly M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run after creating instances in bulk
Parameter name
Parameter fn
A callback function that is called with instances, options
method afterBulkDestroy
static afterBulkDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after destroying instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method afterBulkSync
static afterBulkSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run after sequelize.sync call
Parameter fn
A callback function that is called with options passed to sequelize.sync
method afterBulkUpdate
static afterBulkUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after updating instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method afterCreate
static afterCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after creating a single instance
Parameter name
Parameter fn
A callback function that is called with attributes, options
method afterDestroy
static afterDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void;};
A hook that is run after destroying a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterFind
static afterFind: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instancesOrInstance: readonly M[] | M | null, options: FindOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run after a find (select) query
Parameter name
Parameter fn
A callback function that is called with instance(s), options
method afterSave
static afterSave: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run after creating or updating a single instance, It proxies
afterCreate
andafterUpdate
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterSync
static afterSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run after Model.sync call
Parameter fn
A callback function that is called with options passed to Model.sync
method afterUpdate
static afterUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after updating a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterValidate
static afterValidate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: ValidationOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: ValidationOptions) => HookReturn ): void;};
A hook that is run after validation
Parameter name
Parameter fn
A callback function that is called with instance, options
method aggregate
static aggregate: <T, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M> | '*', aggregateFunction: string, options?: AggregateOptions<T, Attributes<M>>) => Promise<T>;
Run an aggregation method on the specified field
Parameter field
The field to aggregate over. Can be a field name or *
Parameter aggregateFunction
The function to use for aggregation, e.g. sum, max etc.
Parameter options
Query options. See sequelize.query for full options
Returns
Returns the aggregate result cast to
options.dataType
, unlessoptions.plain
is false, in which case the complete data result is returned.
method beforeBulkCreate
static beforeBulkCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instances: M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instances: M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run before creating instances in bulk
Parameter name
Parameter fn
A callback function that is called with instances, options
method beforeBulkDestroy
static beforeBulkDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before destroying instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method beforeBulkSync
static beforeBulkSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run before sequelize.sync call
Parameter fn
A callback function that is called with options passed to sequelize.sync
method beforeBulkUpdate
static beforeBulkUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after updating instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method beforeCount
static beforeCount: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: CountOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: CountOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before a count query
Parameter name
Parameter fn
A callback function that is called with options
method beforeCreate
static beforeCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before creating a single instance
Parameter name
Parameter fn
A callback function that is called with attributes, options
method beforeDestroy
static beforeDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void;};
A hook that is run before destroying a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeFind
static beforeFind: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before a find (select) query
Parameter name
Parameter fn
A callback function that is called with options
method beforeFindAfterExpandIncludeAll
static beforeFindAfterExpandIncludeAll: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
Parameter name
Parameter fn
A callback function that is called with options
method beforeFindAfterOptions
static beforeFindAfterOptions: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => void ): HookReturn;};
A hook that is run before a find (select) query, after all option parsing is complete
Parameter name
Parameter fn
A callback function that is called with options
method beforeSave
static beforeSave: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run before creating or updating a single instance, It proxies
beforeCreate
andbeforeUpdate
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeSync
static beforeSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run before Model.sync call
Parameter fn
A callback function that is called with options passed to Model.sync
method beforeUpdate
static beforeUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before updating a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeValidate
static beforeValidate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: ValidationOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: ValidationOptions) => HookReturn ): void;};
A hook that is run before validation
Parameter name
Parameter fn
A callback function that is called with instance, options
method belongsTo
static belongsTo: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options?: BelongsToOptions) => BelongsTo<M, T>;
Creates an association between this (the source) and the provided target. The foreign key is added on the source.
Example:
Profile.belongsTo(User)
. This will add userId to the profile table.Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method belongsToMany
static belongsToMany: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options: BelongsToManyOptions) => BelongsToMany<M, T>;
Create an N:M association with a join table
User.belongsToMany(Project)Project.belongsToMany(User)By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as
through
in the options.If you use a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before with a join table that stores whether the project has been started yet:
class UserProjects extends Model {}UserProjects.init({started: Sequelize.BOOLEAN}, { sequelize });User.belongsToMany(Project, { through: UserProjects })Project.belongsToMany(User, { through: UserProjects })jan.addProject(homework, { started: false }) // The homework project is not started yetjan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been startedIf you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
p1.userprojects {started: true}user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.Similarily, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
user.getProjects().then(projects => {const p1 = projects[0]p1.userprojects.started // Is this project started yet?})Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method build
static build: <M extends Model<any, any>>( this: ModelStatic<M>, record?: CreationAttributes<M>, options?: BuildOptions) => M;
Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
method bulkBuild
static bulkBuild: <M extends Model<any, any>>( this: ModelStatic<M>, records: ReadonlyArray<CreationAttributes<M>>, options?: BuildOptions) => M[];
Undocumented bulkBuild
method bulkCreate
static bulkCreate: <M extends Model<any, any>>( this: ModelStatic<M>, records: ReadonlyArray<CreationAttributes<M>>, options?: BulkCreateOptions<Attributes<M>>) => Promise<M[]>;
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.
Parameter records
List of objects (key/value pairs) to create instances from
method changed
changed: { <K extends keyof this>(key: K): boolean; <K extends keyof this>(key: K, dirty: boolean): void; (): false | string[];};
If changed is called with a string it will return a boolean indicating whether the value of that key in
dataValues
is different from the value in_previousDataValues
.If changed is called without an argument, it will return an array of keys that have changed.
If changed is called with two arguments, it will set the property to
dirty
.If changed is called without an argument and no keys have changed, it will return
false
.
method count
static count: { <M extends Model<any, any>>( this: ModelStatic<M>, options: CountWithOptions<Attributes<M>> ): Promise<GroupedCountResultItem[]>; <M extends Model<any, any>>( this: ModelStatic<M>, options?: Omit<CountOptions<Attributes<M>>, 'group'> ): Promise<number>;};
Count number of records if group by is used
Returns
Returns count for each group and the projected attributes.
Count the number of records matching the provided where clause.
If you provide an
include
option, the number of matching associations will be counted instead.Returns
Returns count for each group and the projected attributes.
method create
static create: < M extends Model<any, any>, O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>>( this: ModelStatic<M>, values?: CreationAttributes<M>, options?: O) => Promise< O extends { returning: false } | { ignoreDuplicates: true } ? void : M>;
Builds a new model instance and calls save on it.
method decrement
static decrement: { <M extends Model<any, any>>( this: ModelStatic<M>, fields: AllowReadonlyArray<keyof Attributes<M>>, options: IncrementDecrementOptionsWithBy<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>; <M extends Model<any, any>>( this: ModelStatic<M>, fields: { [key in keyof Attributes<M>]?: number }, options: IncrementDecrementOptions<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>;};
Decrements the value of one or more attributes.
Works like Model.increment
Parameter fields
If a string is provided, that column is incremented by the value of
by
given in options. If an array is provided, the same is true for each column. If an object is provided, each key is incremented by the corresponding value,by
is ignored.Returns
an array of affected rows or with affected count if
options.returning
is true, whenever supported by dialect4.36.0
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 - Xquery. To get the correct value after an decrement into the Instance you should do a reload.
instance.decrement('number') // decrement number by 1instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.// `by` is ignored, since each column has its own// valueParameter fields
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
method describe
static describe: () => Promise<object>;
Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.
method destroy
static destroy: <M extends Model<any, any>>( this: ModelStatic<M>, options?: DestroyOptions<Attributes<M>>) => Promise<number>;
Delete multiple instances, or set their deletedAt timestamp to the current time if
paranoid
is enabled.Returns
Promise The number of destroyed rows
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.
method drop
static drop: (options?: DropOptions) => Promise<void>;
Drop the table represented by this Model
Parameter options
method equals
equals: (other: this) => boolean;
Check whether all values of this and
other
Instance are the same
method equalsOneOf
equalsOneOf: (others: readonly this[]) => boolean;
Check if this is equal to one of
others
by calling equals
method findAll
static findAll: <M extends Model<any, any>>( this: ModelStatic<M>, options?: FindOptions<Attributes<M>>) => Promise<M[]>;
Search for multiple instances.
__Simple search using AND and =__
Model.findAll({where: {attr1: 42,attr2: 'cake'}})WHERE attr1 = 42 AND attr2 = 'cake'__Using greater than, less than etc.__
Model.findAll({where: {attr1: {gt: 50},attr2: {lte: 45},attr3: {in: [1,2,3]},attr4: {ne: 5}}})WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5Possible options are: `[Op.ne], [Op.in], [Op.not], [Op.notIn], [Op.gte], [Op.gt], [Op.lte], [Op.lt], [Op.like], [Op.ilike]/[Op.iLike], [Op.notLike], [Op.notILike], '..'/[Op.between], '!..'/[Op.notBetween], '&&'/[Op.overlap], '@>'/[Op.contains], '<@'/[Op.contained]`
__Queries using OR__
Model.findAll({where: Sequelize.and({ name: 'a project' },Sequelize.or({ id: [1,2,3] },{ id: { gt: 10 } }))})WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)The success listener is called with an array of instances if the query succeeds.
See Also
{Sequelize#query}
method findAndCountAll
static findAndCountAll: { <M extends Model<any, any>>( this: ModelStatic<M>, options?: Omit<FindAndCountOptions<Attributes<M>>, 'group'> ): Promise<{ rows: M[]; count: number }>; <M extends Model<any, any>>( this: ModelStatic<M>, options: { col?: string; type?: string; where?: WhereOptions<Attributes<M>>; include?: Includeable | Includeable[]; order?: Order; limit?: number; groupedLimit?: unknown; offset?: number; lock?: | boolean | LOCK | { level: LOCK; of: ModelStatic<Model<any, any>> }; skipLocked?: boolean; raw?: boolean; having?: WhereOptions<any>; subQuery?: boolean; nest?: boolean; plain?: boolean; replacements?: BindOrReplacements; bind?: BindOrReplacements; instance?: Model<any, any>; mapToModel?: boolean; retry?: RetryAsPromisedOptions; fieldMap?: FieldMap; logging?: boolean | ((sql: string, timing?: number) => void); benchmark?: boolean; transaction?: Transaction; useMaster?: boolean; attributes?: FindAttributeOptions; paranoid?: boolean; indexHints?: IndexHint[]; distinct?: boolean; group: GroupOption; } ): Promise<{ rows: M[]; count: GroupedCountResultItem[] }>;};
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
Model.findAndCountAll({where: ...,limit: 12,offset: 12}).then(result => {...})In the above example,
result.rows
will contain rows 13 through 24, whileresult.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
hasrequired
set it will result in an inner join, and only the users who have a profile will be counted. If we removerequired
from the include, both users with and without profiles will be countedThis 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'});
method findByPk
static findByPk: { <M extends Model<any, any>>( this: ModelStatic<M>, identifier: Identifier, options: Omit<NonNullFindOptions<Attributes<M>>, 'where'> ): Promise<M>; <M extends Model<any, any>>( this: ModelStatic<M>, identifier?: any, options?: Omit<FindOptions<Attributes<M>>, 'where'> ): Promise<M>;};
Search for a single instance by its primary key. This applies LIMIT 1, so the listener will always be called with a single instance.
method findCreateFind
static findCreateFind: <M extends Model<any, any>>( this: ModelStatic<M>, options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>) => Promise<[M, boolean]>;
A more performant findOrCreate that will not work under a transaction (at least not in postgres) Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
method findOne
static findOne: { <M extends Model<any, any>>( this: ModelStatic<M>, options: NonNullFindOptions<Attributes<M>> ): Promise<M>; <M extends Model<any, any>>( this: ModelStatic<M>, options?: FindOptions<Attributes<M>> ): Promise<M>;};
Search for a single instance. Returns the first instance found, or null if none can be found.
method findOrBuild
static findOrBuild: <M extends Model<any, any>>( this: ModelStatic<M>, options: FindOrBuildOptions<Attributes<M>, CreationAttributes<M>>) => Promise<[M, 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, initialized) - Make sure to use
.then(([...]))
method findOrCreate
static findOrCreate: <M extends Model<any, any>>( this: ModelStatic<M>, options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>) => Promise<[M, 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) - Make sure to use
.then(([...]))
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 comitted. 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.
method get
get: { (options?: { plain?: boolean; clone?: boolean }): TModelAttributes; <K extends keyof this>( key: K, options?: { plain?: boolean; clone?: boolean } ): this[K]; (key: string, options?: { plain?: boolean; clone?: boolean }): unknown;};
If no key is given, returns all values of the instance, also invoking virtual getters.
If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
Parameter
options.plain If set to true, included instances will be returned as plain objects
method getAttributes
static getAttributes: <M extends Model<any, any>>( this: ModelStatic<M>) => { readonly [Key in keyof Attributes<M>]: ModelAttributeColumnOptions< Model<any, any> >;};
Returns the attributes of the model
method getDataValue
getDataValue: <K extends keyof TModelAttributes>(key: K) => TModelAttributes[K];
Get the value of the underlying data value
method getTableName
static getTableName: () => | string | { tableName: string; schema: string; delimiter: string };
Get the tablename 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
anddelimiter
properties.Parameter options
The hash of options from any query. You can use one model to access tables with matching schemas by overriding
getTableName
and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)
method hasMany
static hasMany: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options?: HasManyOptions) => HasMany<M, T>;
Create an association that is either 1:m or n:m.
// Create a 1:m association between user and projectUser.hasMany(Project)// Create a n:m association between user and projectUser.hasMany(Project)Project.hasMany(User)By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as
through
in the options. If you use a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before with a join table that stores whether the project has been started yet:class UserProjects extends Model {}UserProjects.init({started: Sequelize.BOOLEAN}, { sequelize })User.hasMany(Project, { through: UserProjects })Project.hasMany(User, { through: UserProjects })jan.addProject(homework, { started: false }) // The homework project is not started yetjan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have beenstartedIf you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
p1.userprojects {started: true}user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.Similarily, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
user.getProjects().then(projects => {const p1 = projects[0]p1.userprojects.started // Is this project started yet?})Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method hasOne
static hasOne: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options?: HasOneOptions) => HasOne<M, T>;
Creates an association between this (the source) and the provided target. The foreign key is added on the target.
Example:
User.hasOne(Profile)
. This will add userId to the profile table.Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method increment
static increment: { <M extends Model<any, any>>( this: ModelStatic<M>, fields: AllowReadonlyArray<keyof Attributes<M>>, options: IncrementDecrementOptionsWithBy<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>; <M extends Model<any, any>>( this: ModelStatic<M>, fields: { [key in keyof Attributes<M>]?: number }, options: IncrementDecrementOptions<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>;};
Increments the value of one or more attributes.
The increment is done using a
SET column = column + X WHERE foo = 'bar'
query.Parameter fields
If a string is provided, that column is incremented by the value of
by
given in options. If an array is provided, the same is true for each column. If an object is provided, each key is incremented by the corresponding value,by
is ignored.Returns
an array of affected rows or with affected count if
options.returning
is true, whenever supported by dialectExample 1
increment number by 1
Model.increment('number', { where: { foo: 'bar' });Example 2
increment number and count by 2
Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });Example 3
increment answer by 42, and decrement tries by 1
// `by` cannot be used, as each attribute specifies its own valueModel.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } });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 + Xquery. To get the correct value after an increment into the Instance you should do a reload.
instance.increment('number') // increment number by 1instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.// `by` is ignored, since each column has its own// valueParameter fields
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.
method init
static init: < MS extends ModelStatic<Model<any, any>>, M extends InstanceType<MS>>( this: MS, attributes: ModelAttributes< M, Optional< Attributes<M>, BrandedKeysOf<Attributes<M>, typeof ForeignKeyBrand> > >, options: InitOptions<M>) => MS;
Initialize a model, representing a table in the DB, with attributes and options.
The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
Project.init({columnA: {type: Sequelize.BOOLEAN,validate: {is: ['[a-z]','i'], // will only allow lettersmax: 23, // only allow values <= 23isIn: {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 nameAs shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
For a list of possible data types, see https://sequelize.org/master/en/latest/docs/models-definition/#data-types
For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters
For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models
For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations
Parameter attributes
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:
Parameter options
These options are merged with the default define options provided to the Sequelize constructor
Returns
Return the initialized model
method isSoftDeleted
isSoftDeleted: () => boolean;
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.
Throws an error if paranoid is not enabled.
method max
static max: <T extends unknown, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>) => Promise<T>;
Find the maximum value of field
method min
static min: <T extends unknown, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>) => Promise<T>;
Find the minimum value of field
method previous
previous: { (): Partial<TModelAttributes>; <K extends keyof TModelAttributes>(key: K): TModelAttributes[K];};
Returns the previous value for key from
_previousDataValues
.
method reload
reload: (options?: FindOptions<TModelAttributes>) => Promise<this>;
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.
method removeAttribute
static removeAttribute: (attribute: string) => void;
Remove attribute from model definition
Parameter attribute
method restore
static restore: <M extends Model<any, any>>( this: ModelStatic<M>, options?: RestoreOptions<Attributes<M>>) => Promise<void>;
Restore multiple instances if
paranoid
is enabled.Restore the row corresponding to this instance. Only available for paranoid models.
method save
save: (options?: SaveOptions<TModelAttributes>) => Promise<this>;
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.
method schema
static schema: <M extends Model<any, any>>( this: ModelStatic<M>, schema: string, options?: SchemaOptions) => ModelCtor<M>;
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'
.Parameter schema
The name of the schema
Parameter options
method scope
static scope: <M extends Model<any, any>>( this: ModelStatic<M>, options?: | string | ScopeOptions | readonly (string | ScopeOptions)[] | WhereAttributeHash<M>) => ModelCtor<M>;
Apply a scope created in
define
to the model. First let's look at how to create scopes:class MyModel extends Model {}MyModel.init(attributes, {defaultScope: {where: {username: 'dan'},limit: 12},scopes: {isALie: {where: {stuff: 'cake'}},complexFunction(email, accessLevel) {return {where: {email: {[Op.like]: email},accesss_level {[Op.gte]: accessLevel}}}}},sequelize,})Now, since you 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: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'To invoke scope functions you can do:
Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()// WHERE email like 'dan@sequelize.com%' AND access_level >= 42Returns
Model A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
method set
set: { <K extends keyof TModelAttributes>( key: K, value: TModelAttributes[K], options?: SetOptions ): this; (keys: Partial<TModelAttributes>, options?: SetOptions): this;};
Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call
save
). In its most basic formset
will update a value stored in the underlyingdataValues
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.
Parameter
options.raw If set to true, field and virtual setters will be ignored
Parameter
options.reset Clear all previously set data values
method setAttributes
setAttributes: { <K extends keyof TModelAttributes>( key: K, value: TModelAttributes[K], options?: SetOptions ): this; (keys: Partial<TModelAttributes>, options?: SetOptions): this;};
method setDataValue
setDataValue: <K extends keyof TModelAttributes>( key: K, value: TModelAttributes[K]) => void;
Update the underlying data value
method sum
static sum: <T extends unknown, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>) => Promise<number>;
Find the sum of field
method sync
static sync: <M extends Model<any, any>>(options?: SyncOptions) => Promise<M>;
Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
method toJSON
toJSON: { <T extends TModelAttributes>(): T; (): object };
Convert the instance to a JSON representation. Proxies to calling
get
with no keys. This means get all values gotten from the DB, and apply all custom getters.
method truncate
static truncate: <M extends Model<any, any>>( this: ModelStatic<M>, options?: TruncateOptions<Attributes<M>>) => Promise<void>;
Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
method unscoped
static unscoped: <M extends ModelType<any, any>>(this: M) => M;
Unscope the model
method update
static update: { <M extends Model<any, any>>( this: ModelStatic<M>, values: { [key in keyof Attributes<M>]?: | Fn | Col | Literal | Attributes<M>[key]; }, options: Omit<UpdateOptions<Attributes<M>>, 'returning'> & { returning: Exclude< UpdateOptions<Attributes<M>>['returning'], undefined | false >; } ): Promise<[affectedCount: number, affectedRows: M[]]>; <M extends Model<any, any>>( this: ModelStatic<M>, values: { [key in keyof Attributes<M>]?: | Fn | Col | Literal | Attributes<M>[key]; }, options: UpdateOptions<Attributes<M>> ): Promise<[affectedCount: number]>;};
Update multiple instances that match the where options. 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 and mssql with
options.returning
true.)This is the same as calling
set
and then callingsave
.
method upsert
static upsert: <M extends Model<any, any>>( this: ModelStatic<M>, values: CreationAttributes<M>, options?: UpsertOptions<Attributes<M>>) => Promise<[M, boolean | null]>;
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 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 queriesINSERT; UPDATE
. This means that the update is executed regardless of whether the row already existed or not**Note** that 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.
method validate
validate: (options?: ValidationOptions) => Promise<void>;
Validate the attribute of this instance according to validation rules set in the model definition.
Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.
Parameter
options.skip An array of strings. All properties that are in this array will not be validated
method where
where: () => object;
Get an object representing the query for this instance, use with
options.where
class OptimisticLockError
class OptimisticLockError extends BaseError {}
Thrown when attempting to update a stale model instance
constructor
constructor(options: OptimisticLockErrorOptions);
property modelName
modelName: string;
property values
values: Record<string, unknown>;
property where
where: Record<string, unknown>;
class QueryError
class QueryError extends BaseError {}
Thrown when a query is passed invalid options (see message for details)
constructor
constructor(message: string);
class QueryInterface
class QueryInterface {}
The interface that Sequelize uses to talk to all databases.
This interface is available through sequelize.queryInterface. It should not be commonly used, but it's referenced anyway, so it can be used.
constructor
constructor(sequelize: Sequelize);
property queryGenerator
queryGenerator: {};
Returns the dialect-specific sql generator.
We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
property sequelize
sequelize: Sequelize;
Returns the current sequelize instance.
method addColumn
addColumn: ( table: TableName, key: string, attribute: ModelAttributeColumnOptions | DataType, options?: QueryInterfaceOptions) => Promise<void>;
Adds a new column to a table
method addConstraint
addConstraint: ( tableName: TableName, options?: AddConstraintOptions & QueryInterfaceOptions) => Promise<void>;
Adds constraints to a table
method addIndex
addIndex: { ( tableName: TableName, attributes: string[], options?: QueryInterfaceIndexOptions, rawTablename?: string ): Promise<void>; ( tableName: TableName, options: { type?: IndexType; where?: WhereOptions<any>; logging?: boolean | ((sql: string, timing?: number) => void); benchmark?: boolean; transaction?: Transaction; unique?: boolean; name?: string; parser?: string; concurrently?: boolean; using?: string; operator?: string; prefix?: string; fields: ( | string | Fn | Literal | { name: string; length?: number; order?: 'ASC' | 'DESC'; collate?: string; operator?: string; } )[]; }, rawTablename?: string ): Promise<void>;};
Adds a new index to a table
method bulkDelete
bulkDelete: ( tableName: TableName, identifier: WhereOptions<any>, options?: QueryOptions, model?: ModelType) => Promise<object>;
Deletes multiple rows at once
method bulkInsert
bulkInsert: ( tableName: TableName, records: object[], options?: QueryOptions, attributes?: Record<string, ModelAttributeColumnOptions>) => Promise<object | number>;
Inserts multiple records at once
method bulkUpdate
bulkUpdate: ( tableName: TableName, values: object, identifier: WhereOptions<any>, options?: QueryOptions, attributes?: string[] | string) => Promise<object>;
Updates multiple rows at once
method changeColumn
changeColumn: ( tableName: TableName, attributeName: string, dataTypeOrOptions?: DataType | ModelAttributeColumnOptions, options?: QueryInterfaceOptions) => Promise<void>;
Changes a column
method commitTransaction
commitTransaction: ( transaction: Transaction, options?: QueryOptions) => Promise<void>;
Commit an already started transaction
method createDatabase
createDatabase: (name: string, options?: CreateDatabaseOptions) => Promise<void>;
Creates a database
method createFunction
createFunction: ( functionName: string, params: FunctionParam[], returnType: string, language: string, body: string, optionsArray?: string[], options?: QueryOptionsWithForce) => Promise<void>;
Postgres only. Create a function
method createSchema
createSchema: ( schema?: string, options?: QueryInterfaceOptions) => Promise<void>;
Queries the schema (table list).
Parameter schema
The schema to query. Applies only to Postgres.
method createTable
createTable: <M extends Model<any, any>>( tableName: TableName, attributes: ModelAttributes<M, CreationAttributes<M>>, options?: QueryInterfaceCreateTableOptions) => Promise<void>;
Creates a table with specified attributes.
Parameter tableName
Name of table to create
Parameter attributes
Hash of attributes, key is attribute name, value is data type
Parameter options
Table options.
method createTrigger
createTrigger: ( tableName: TableName, triggerName: string, timingType: string, fireOnArray: { [key: string]: unknown }[], functionName: string, functionParams: FunctionParam[], optionsArray: string[], options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters.
method databaseVersion
databaseVersion: (options?: QueryInterfaceOptions) => Promise<string>;
Return database version
method deferConstraints
deferConstraints: ( transaction: Transaction, options?: QueryOptions) => Promise<void>;
Defer constraints
method delete
delete: ( instance: Model | null, tableName: TableName, identifier: WhereOptions<any>, options?: QueryOptions) => Promise<object>;
Deletes a row
method describeTable
describeTable: ( tableName: TableName, options?: string | ({ schema?: string; schemaDelimiter?: string } & Logging)) => Promise<ColumnsDescription>;
Describe a table
method dropAllEnums
dropAllEnums: (options?: QueryOptions) => Promise<void>;
Drops all defined enums
Parameter options
method dropAllSchemas
dropAllSchemas: (options?: QueryInterfaceDropAllTablesOptions) => Promise<void>;
Drops all tables.
method dropAllTables
dropAllTables: (options?: QueryInterfaceDropAllTablesOptions) => Promise<void>;
Drops all tables.
Parameter options
method dropDatabase
dropDatabase: (name: string, options?: QueryOptions) => Promise<void>;
Creates a database
method dropFunction
dropFunction: ( functionName: string, params: FunctionParam[], options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Drops a function
method dropSchema
dropSchema: (schema?: string, options?: QueryInterfaceOptions) => Promise<void>;
Drops the specified schema (table).
Parameter schema
The schema to query. Applies only to Postgres.
method dropTable
dropTable: ( tableName: TableName, options?: QueryInterfaceDropTableOptions) => Promise<void>;
Drops the specified table.
Parameter tableName
Table name.
Parameter options
Query options, particularly "force".
method dropTrigger
dropTrigger: ( tableName: TableName, triggerName: string, options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Drops the specified trigger.
method getForeignKeyReferencesForTable
getForeignKeyReferencesForTable: ( tableName: TableName, options?: QueryInterfaceOptions) => Promise<object>;
Get foreign key references details for the table
method getForeignKeysForTables
getForeignKeysForTables: ( tableNames: string[], options?: QueryInterfaceOptions) => Promise<object>;
Returns all foreign key constraints of requested tables
method increment
increment: <M extends Model<any, any>>( instance: Model, tableName: TableName, values: object, identifier: WhereOptions<Attributes<M>>, options?: QueryOptions) => Promise<object>;
Increments a row value
method insert
insert: ( instance: Model | null, tableName: string, values: object, options?: QueryOptions) => Promise<object>;
Inserts a new record
method nameIndexes
nameIndexes: (indexes: string[], rawTablename: string) => Promise<void>;
Put a name to an index
method quoteIdentifier
quoteIdentifier: (identifier: string, force?: boolean) => string;
Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted even if the
quoteIdentifiers
option is false.
method quoteIdentifiers
quoteIdentifiers: (identifiers: string) => string;
Split an identifier into .-separated tokens and quote each part.
method quoteTable
quoteTable: (identifier: TableName) => string;
Escape a table name
method rawSelect
rawSelect: ( tableName: TableName, options: QueryOptionsWithWhere, attributeSelector: string | string[], model?: ModelType) => Promise<string[]>;
Selects raw without parsing the string into an object
method removeColumn
removeColumn: ( table: TableName, attribute: string, options?: QueryInterfaceOptions) => Promise<void>;
Removes a column from a table
method removeConstraint
removeConstraint: ( tableName: TableName, constraintName: string, options?: QueryInterfaceOptions) => Promise<void>;
Removes constraints from a table
method removeIndex
removeIndex: { ( tableName: TableName, indexName: string, options?: QueryInterfaceIndexOptions ): Promise<void>; ( tableName: TableName, attributes: string[], options?: QueryInterfaceIndexOptions ): Promise<void>;};
Removes an index of a table
method renameColumn
renameColumn: ( tableName: TableName, attrNameBefore: string, attrNameAfter: string, options?: QueryInterfaceOptions) => Promise<void>;
Renames a column
method renameFunction
renameFunction: ( oldFunctionName: string, params: FunctionParam[], newFunctionName: string, options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Rename a function
method renameTable
renameTable: ( before: TableName, after: TableName, options?: QueryInterfaceOptions) => Promise<void>;
Renames a table
method renameTrigger
renameTrigger: ( tableName: TableName, oldTriggerName: string, newTriggerName: string, options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Renames a trigger
method rollbackTransaction
rollbackTransaction: ( transaction: Transaction, options?: QueryOptions) => Promise<void>;
Rollback ( revert ) a transaction that has'nt been commited
method select
select: ( model: ModelType | null, tableName: TableName, options?: QueryOptionsWithWhere) => Promise<object[]>;
Returns selected rows
method setAutocommit
setAutocommit: ( transaction: Transaction, value: boolean, options?: QueryOptions) => Promise<void>;
Set option for autocommit of a transaction
method setIsolationLevel
setIsolationLevel: ( transaction: Transaction, value: string, options?: QueryOptions) => Promise<void>;
Set the isolation level of a transaction
method showAllSchemas
showAllSchemas: (options?: QueryOptions) => Promise<object>;
Queries all table names in the database.
Parameter options
method showAllTables
showAllTables: (options?: QueryOptions) => Promise<string[]>;
Returns all tables
method showIndex
showIndex: ( tableName: string | object, options?: QueryOptions) => Promise<object>;
Shows the index of a table
method startTransaction
startTransaction: ( transaction: Transaction, options?: QueryOptions) => Promise<void>;
Begin a new transaction
method tableExists
tableExists: (tableName: TableName, options?: QueryOptions) => Promise<boolean>;
Returns a promise that resolves to true if the table exists in the database, false otherwise.
Parameter tableName
The name of the table
Parameter options
Options passed to Sequelize#query
method update
update: <M extends Model<any, any>>( instance: M, tableName: TableName, values: object, identifier: WhereOptions<Attributes<M>>, options?: QueryOptions) => Promise<object>;
Updates a row
method upsert
upsert: <M extends Model<any, any>>( tableName: TableName, insertValues: object, updateValues: object, where: object, options?: QueryOptionsWithModel<M>) => Promise<object>;
Inserts or Updates a record in the database
class Sequelize
class Sequelize extends Hooks {}
This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
const Sequelize = require('sequelize');In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
constructor
constructor( database: string, username: string, password?: string, options?: Options);
Instantiate sequelize with name of database, username and password
#### Example usage
// without password and optionsconst sequelize = new Sequelize('database', 'username')// without optionsconst sequelize = new Sequelize('database', 'username', 'password')// without password / with blank passwordconst sequelize = new Sequelize('database', 'username', null, {})// with password and optionsconst sequelize = new Sequelize('my_database', 'john', 'doe', {})// with uri (see below)const sequelize = new Sequelize('mysql://localhost:3306/database', {})Parameter database
The name of the database
Parameter username
The username which is used to authenticate against the database.
Parameter password
The password which is used to authenticate against the database.
Parameter options
An object with options.
constructor
constructor(database: string, username: string, options?: Options);
constructor
constructor(options?: Options);
constructor
constructor(uri: string, options?: Options);
Instantiate sequelize with an URI
Parameter uri
A full database URI
Parameter options
See above for possible options
property and
static and: <T extends any[]>(...args: T) => { [OpTypes.and]: T };
An AND query
Parameter args
Each argument will be joined by AND
property and
and: <T extends any[]>(...args: T) => { [OpTypes.and]: T };
property cast
static cast: (val: unknown, type: string) => Cast;
Creates a object representing a call to the cast function.
Parameter val
The value to cast
Parameter type
The type to cast it to
property cast
cast: (val: unknown, type: string) => Cast;
property col
static col: (col: string) => Col;
Creates a object representing a column in the DB. This is often useful in conjunction with
sequelize.fn
, since raw string arguments to fn will be escaped.Parameter col
The name of the column
property col
col: (col: string) => Col;
property config
readonly config: Config;
Final config that is used by sequelize.
property connectionManager
readonly connectionManager: ConnectionManager;
property fn
static fn: (fn: string, ...args: unknown[]) => Fn;
Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. If you want to refer to columns in your function, you should use
sequelize.col
, so that the columns are properly interpreted as columns and not a strings.Convert a user's username to upper case
instance.update({username: self.sequelize.fn('upper', self.sequelize.col('username'))})Parameter fn
The function you want to call
Parameter args
All further arguments will be passed as arguments to the function
property fn
fn: (fn: string, ...args: unknown[]) => Fn;
property json
static json: ( conditionsOrPath: string | object, value?: string | number | boolean) => Json;
Creates an object representing nested where conditions for postgres's json data-type.
Parameter conditionsOrPath
A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
Parameter value
An optional value to compare against. Produces a string of the form "<json path> = ''".
property json
json: ( conditionsOrPath: string | object, value?: string | number | boolean) => Json;
property literal
static literal: (val: string) => Literal;
Creates a object representing a literal, i.e. something that will not be escaped.
Parameter val
property literal
literal: (val: string) => Literal;
property modelManager
readonly modelManager: ModelManager;
property models
readonly models: { [key: string]: ModelCtor<Model<any, any>> };
Dictionary of all models linked with this instance.
property or
static or: <T extends any[]>(...args: T) => { [OpTypes.or]: T };
An OR query
Parameter args
Each argument will be joined by OR
property or
or: <T extends any[]>(...args: T) => { [OpTypes.or]: T };
property Sequelize
Sequelize: typeof Sequelize;
A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
property where
static where: { <Op extends keyof WhereOperators<any>>( leftOperand: Where | WhereLeftOperand, operator: Op, rightOperand: WhereOperators<any>[Op] ): Where; <Op extends keyof WhereOperators<any>>( leftOperand: any, operator: string, rightOperand: any ): Where; (leftOperand: WhereLeftOperand, rightOperand: any): Where;};
A way of specifying attr = condition.
The attr can either be an object taken from
Model.rawAttributes
(for exampleModel.rawAttributes.id
orModel.rawAttributes.name
). The attribute should be defined in your model definition. The attribute can also be an object from one of the sequelize utility functions (sequelize.fn
,sequelize.col
etc.)For string attributes, use the regular
{ where: { attr: something }}
syntax. If you don't want your string to be escaped, usesequelize.literal
.Parameter attr
The attribute, which can be either an attribute object from
Model.rawAttributes
or a sequelize object, for example an instance ofsequelize.fn
. For simple string attributes, use the POJO syntaxParameter comparator
Comparator
Parameter logic
The condition. Can be both a simply type, or a further condition (
.or
,.and
,.literal
etc.)
property where
where: { <Op extends keyof WhereOperators<any>>( leftOperand: Where | WhereLeftOperand, operator: Op, rightOperand: WhereOperators<any>[Op] ): Where; <Op extends keyof WhereOperators<any>>( leftOperand: any, operator: string, rightOperand: any ): Where; (leftOperand: WhereLeftOperand, rightOperand: any): Where;};
method afterBulkCreate
static afterBulkCreate: { ( name: string, fn: (instances: Model[], options: BulkCreateOptions<any>) => void ): void; ( fn: ( instances: Model<any, any>[], options: BulkCreateOptions<any> ) => void ): void;};
A hook that is run after creating instances in bulk
Parameter name
Parameter fn
A callback function that is called with instances, options
method afterBulkDestroy
static afterBulkDestroy: { (name: string, fn: (options: DestroyOptions<any>) => void): void; (fn: (options: DestroyOptions<any>) => void): void;};
A hook that is run after destroying instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method afterBulkSync
static afterBulkSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run after sequelize.sync call
Parameter fn
A callback function that is called with options passed to sequelize.sync
method afterBulkUpdate
static afterBulkUpdate: { (name: string, fn: (options: UpdateOptions<any>) => void): void; (fn: (options: UpdateOptions<any>) => void): void;};
A hook that is run after updating instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method afterConnect
static afterConnect: { (name: string, fn: (connection: unknown, options: Config) => void): void; (fn: (connection: unknown, options: Config) => void): void;};
A hook that is run after a connection is established
Parameter name
Parameter fn
A callback function that is called with options
method afterCreate
static afterCreate: { ( name: string, fn: (attributes: Model, options: CreateOptions<any>) => void ): void; ( fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void ): void;};
A hook that is run after creating a single instance
Parameter name
Parameter fn
A callback function that is called with attributes, options
method afterDefine
static afterDefine: { (name: string, fn: (model: ModelType) => void): void; (fn: (model: ModelType<any, any>) => void): void;};
A hook that is run after a define call
Parameter name
Parameter fn
A callback function that is called with factory
method afterDestroy
static afterDestroy: { ( name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void ): void; ( fn: (instance: Model<any, any>, options: InstanceDestroyOptions) => void ): void;};
A hook that is run after destroying a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterDisconnect
static afterDisconnect: { (name: string, fn: (connection: unknown) => void): void; (fn: (connection: unknown) => void): void;};
A hook that is run after a connection is released
Parameter name
Parameter fn
A callback function that is called with options
method afterFind
static afterFind: { ( name: string, fn: ( instancesOrInstance: Model[] | Model | null, options: FindOptions<any> ) => void ): void; ( fn: ( instancesOrInstance: Model<any, any> | Model<any, any>[], options: FindOptions<any> ) => void ): void;};
A hook that is run after a find (select) query
Parameter name
Parameter fn
A callback function that is called with instance(s), options
method afterInit
static afterInit: { (name: string, fn: (sequelize: Sequelize) => void): void; (fn: (sequelize: Sequelize) => void): void;};
A hook that is run after Sequelize() call
Parameter name
Parameter fn
A callback function that is called with sequelize
method afterPoolAcquire
static afterPoolAcquire: { ( name: string, fn: (connection: Connection, options: GetConnectionOptions) => void ): void; (fn: (connection: object, options: GetConnectionOptions) => void): void;};
A hook that is run after successfully acquiring a connection from the pool
Parameter name
Parameter fn
A callback function that is called with options
method afterSave
static afterSave: { ( name: string, fn: ( instance: Model, options: UpdateOptions<any> | CreateOptions<any> ) => void ): void; ( fn: ( instance: Model<any, any>, options: CreateOptions<any> | UpdateOptions<any> ) => void ): void;};
A hook that is run after creating or updating a single instance, It proxies
afterCreate
andafterUpdate
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterSync
static afterSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run after Model.sync call
Parameter fn
A callback function that is called with options passed to Model.sync
method afterUpdate
static afterUpdate: { ( name: string, fn: (instance: Model, options: UpdateOptions<any>) => void ): void; (fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void;};
A hook that is run after updating a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterValidate
static afterValidate: { ( name: string, fn: (instance: Model, options: ValidationOptions) => void ): void; (fn: (instance: Model<any, any>, options: ValidationOptions) => void): void;};
A hook that is run after validation
Parameter name
Parameter fn
A callback function that is called with instance, options
method authenticate
authenticate: (options?: QueryOptions) => Promise<void>;
Test the connection by trying to authenticate
Parameter options
Query Options for authentication
method beforeBulkCreate
static beforeBulkCreate: { ( name: string, fn: (instances: Model[], options: BulkCreateOptions<any>) => void ): void; ( fn: ( instances: Model<any, any>[], options: BulkCreateOptions<any> ) => void ): void;};
A hook that is run before creating instances in bulk
Parameter name
Parameter fn
A callback function that is called with instances, options
method beforeBulkDestroy
static beforeBulkDestroy: { (name: string, fn: (options: BulkCreateOptions<any>) => void): void; (fn: (options: BulkCreateOptions<any>) => void): void;};
A hook that is run before destroying instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method beforeBulkSync
static beforeBulkSync: { (dname: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run before sequelize.sync call
Parameter fn
A callback function that is called with options passed to sequelize.sync
method beforeBulkUpdate
static beforeBulkUpdate: { (name: string, fn: (options: UpdateOptions<any>) => void): void; (fn: (options: UpdateOptions<any>) => void): void;};
A hook that is run after updating instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method beforeConnect
static beforeConnect: { (name: string, fn: (options: DeepWriteable<Config>) => void): void; (fn: (options: DeepWriteable<Config>) => void): void;};
A hook that is run before a connection is established
Parameter name
Parameter fn
A callback function that is called with options
method beforeCreate
static beforeCreate: { ( name: string, fn: (attributes: Model, options: CreateOptions<any>) => void ): void; ( fn: (attributes: Model<any, any>, options: CreateOptions<any>) => void ): void;};
A hook that is run before creating a single instance
Parameter name
Parameter fn
A callback function that is called with attributes, options
method beforeDefine
static beforeDefine: { <M extends Model<any, any>>( name: string, fn: ( attributes: ModelAttributes<M, CreationAttributes<M>>, options: ModelOptions<M> ) => void ): void; <M extends Model<any, any>>( fn: ( attributes: ModelAttributes< M, MakeNullishOptional<M['_creationAttributes']> >, options: ModelOptions<M> ) => void ): void;};
A hook that is run before a define call
Parameter name
Parameter fn
A callback function that is called with attributes, options
method beforeDestroy
static beforeDestroy: { ( name: string, fn: (instance: Model, options: InstanceDestroyOptions) => void ): void; ( fn: (instance: Model<any, any>, options: InstanceDestroyOptions) => void ): void;};
A hook that is run before destroying a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeDisconnect
static beforeDisconnect: { (name: string, fn: (connection: unknown) => void): void; (fn: (connection: unknown) => void): void;};
A hook that is run before a connection is released
Parameter name
Parameter fn
A callback function that is called with options
method beforeFind
static beforeFind: { (name: string, fn: (options: FindOptions<any>) => void): void; (fn: (options: FindOptions<any>) => void): void;};
A hook that is run before a find (select) query
Parameter name
Parameter fn
A callback function that is called with options
method beforeFindAfterExpandIncludeAll
static beforeFindAfterExpandIncludeAll: { (name: string, fn: (options: FindOptions<any>) => void): void; (fn: (options: FindOptions<any>) => void): void;};
A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
Parameter name
Parameter fn
A callback function that is called with options
method beforeFindAfterOptions
static beforeFindAfterOptions: { (name: string, fn: (options: FindOptions<any>) => void): void; (fn: (options: FindOptions<any>) => void): void;};
A hook that is run before a find (select) query, after all option parsing is complete
Parameter name
Parameter fn
A callback function that is called with options
method beforeInit
static beforeInit: { (name: string, fn: (config: Config, options: Options) => void): void; (fn: (config: Config, options: Options) => void): void;};
A hook that is run before Sequelize() call
Parameter name
Parameter fn
A callback function that is called with config, options
method beforePoolAcquire
static beforePoolAcquire: { (name: string, fn: (options: GetConnectionOptions) => void): void; (fn: (options: GetConnectionOptions) => void): void;};
A hook that is run before attempting to acquire a connection from the pool
Parameter name
Parameter fn
A callback function that is called with options
method beforeSave
static beforeSave: { ( name: string, fn: ( instance: Model, options: UpdateOptions<any> | CreateOptions<any> ) => void ): void; ( fn: ( instance: Model<any, any>, options: CreateOptions<any> | UpdateOptions<any> ) => void ): void;};
A hook that is run before creating or updating a single instance, It proxies
beforeCreate
andbeforeUpdate
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeSync
static beforeSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run before Model.sync call
Parameter fn
A callback function that is called with options passed to Model.sync
method beforeUpdate
static beforeUpdate: { ( name: string, fn: (instance: Model, options: UpdateOptions<any>) => void ): void; (fn: (instance: Model<any, any>, options: UpdateOptions<any>) => void): void;};
A hook that is run before updating a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeValidate
static beforeValidate: { ( name: string, fn: (instance: Model, options: ValidationOptions) => void ): void; (fn: (instance: Model<any, any>, options: ValidationOptions) => void): void;};
A hook that is run before validation
Parameter name
Parameter fn
A callback function that is called with instance, options
method close
close: () => Promise<void>;
Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected.
Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want to garbage collect some of them.
method createSchema
createSchema: (schema: string, options: Logging) => Promise<unknown>;
Create a new database schema.
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), not a database table. In mysql and sqlite, this command will do nothing.
Parameter schema
Name of the schema
Parameter options
Options supplied
method databaseVersion
databaseVersion: () => Promise<string>;
Returns the database version
method define
define: <M extends Model<any, any>, TAttributes = Attributes<M>>( modelName: string, attributes: ModelAttributes<M, TAttributes>, options?: ModelOptions<M>) => ModelCtor<M>;
Define a new model, representing a table in the DB.
The table columns are defined by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
class MyModel extends Model {}MyModel.init({columnA: {type: Sequelize.BOOLEAN,validate: {is: ["[a-z]",'i'], // will only allow lettersmax: 23, // only allow values <= 23isIn: {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 name given to defineAs shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
For a list of possible data types, see https://sequelize.org/master/en/latest/docs/models-definition/#data-types
For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters
For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models
For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations
Parameter modelName
The name of the model. The model will be stored in
sequelize.models
under this nameParameter attributes
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:
Parameter options
These options are merged with the default define options provided to the Sequelize constructor
method drop
drop: (options?: DropOptions) => Promise<unknown[]>;
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
Parameter options
The options passed to each call to Model.drop
method dropAllSchemas
dropAllSchemas: (options: Logging) => Promise<unknown[]>;
Drop all schemas
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
Parameter options
Options supplied
method dropSchema
dropSchema: (schema: string, options: Logging) => Promise<unknown[]>;
Drop a single schema
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), not a database table. In mysql and sqlite, this drop a table matching the schema name
Parameter schema
Name of the schema
Parameter options
Options supplied
method escape
escape: (value: string | number | Date) => string;
Escape value.
Parameter value
Value that needs to be escaped
method getDatabaseName
getDatabaseName: () => string;
Returns the database name.
method getDialect
getDialect: () => string;
Returns the specified dialect.
method getQueryInterface
getQueryInterface: () => QueryInterface;
Returns an instance of QueryInterface.
method isDefined
isDefined: (modelName: string) => boolean;
Checks whether a model with the given name is defined
Parameter modelName
The name of a model defined with Sequelize.define
method model
model: (modelName: string) => ModelCtor<Model>;
Fetch a Model which is already defined
Parameter modelName
The name of a model defined with Sequelize.define
method query
query: { ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.UPDATE> ): Promise<[undefined, number]>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.BULKUPDATE> ): Promise<number>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.INSERT> ): Promise<[number, number]>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.UPSERT> ): Promise<number>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DELETE> ): Promise<void>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.BULKDELETE> ): Promise<number>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SHOWTABLES> ): Promise<string[]>; ( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.DESCRIBE> ): Promise<ColumnsDescription>; <M extends Model<any, any>>( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithModel<M> & { plain: true } ): Promise<M>; <M extends Model<any, any>>( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithModel<M> ): Promise<M[]>; <T extends object>( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SELECT> & { plain: true } ): Promise<T>; <T extends object>( sql: string | { query: string; values: unknown[] }, options: QueryOptionsWithType<QueryTypes.SELECT> ): Promise<T[]>; ( sql: string | { query: string; values: unknown[] }, options: (QueryOptions | QueryOptionsWithType<QueryTypes.RAW>) & { plain: true; } ): Promise<{ [key: string]: unknown }>; ( sql: string | { query: string; values: unknown[] }, options?: QueryOptions | QueryOptionsWithType<QueryTypes.RAW> ): Promise<[unknown[], unknown]>;};
Execute a query on the DB, optionally bypassing all the Sequelize goodness.
By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use
const [results, meta] = await ...
to access the results.If you are running a type of query where you don't need the metadata, for example a
SELECT
query, you can pass in a query type to make sequelize format the results:const [results, metadata] = await sequelize.query('SELECT...'); // Raw query - use array destructuringconst results = await sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }); // SELECT query - no destructuringParameter sql
Parameter options
Query options
method random
random: () => Fn;
Get the fn for random based on the dialect
method set
set: ( variables: object, options: QueryOptionsTransactionRequired) => Promise<unknown>;
Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
Only works for MySQL.
Parameter variables
object with multiple variables.
Parameter options
Query options.
method showAllSchemas
showAllSchemas: (options: Logging) => Promise<object[]>;
Show all defined schemas
Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), not a database table. In mysql and sqlite, this will show all tables.
Parameter options
Options supplied
method sync
sync: (options?: SyncOptions) => Promise<this>;
Sync all defined models to the DB.
Parameter options
Sync Options
method transaction
transaction: { <T>( options: TransactionOptions, autoCallback: (t: Transaction) => PromiseLike<T> ): Promise<T>; <T>(autoCallback: (t: Transaction) => PromiseLike<T>): Promise<T>; (options?: TransactionOptions): Promise<Transaction>;};
Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
try {const transaction = await sequelize.transaction();const user = await User.findOne(..., { transaction });await user.update(..., { transaction });await transaction.commit();} catch(err) {await transaction.rollback();}})A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:
try {await sequelize.transaction(transaction => { // Note that we pass a callback rather than awaiting the call with no argumentsconst user = await User.findOne(..., {transaction});await user.update(..., {transaction});});// Committed} catch(err) {// Rolled backconsole.error(err);}If you have [CLS](https://github.com/Jeff-Lewis/cls-hooked) enabled, the transaction will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
const cls = require('cls-hooked');const namespace = cls.createNamespace('....');const Sequelize = require('sequelize');Sequelize.useCLS(namespace);Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
Parameter options
Transaction Options
Parameter autoCallback
Callback for the transaction
method truncate
truncate: (options?: DestroyOptions<any>) => Promise<unknown[]>;
Truncate all tables defined through the sequelize models. This is done by calling Model.truncate() on each model.
Parameter options
The options passed to Model.destroy in addition to truncate
method useCLS
static useCLS: (namespace: object) => typeof Sequelize;
Use CLS with Sequelize. CLS namespace provided is stored as
Sequelize._cls
and Promise is patched to use the namespace, usingcls-hooked
module.Parameter namespace
method validate
validate: (options?: QueryOptions) => Promise<void>;
class SequelizeScopeError
class SequelizeScopeError extends BaseError {}
Scope Error. Thrown when the sequelize cannot query the specified scope.
constructor
constructor(message: string);
class TimeoutError
class TimeoutError extends DatabaseError {}
Thrown when a database query times out because of a deadlock
constructor
constructor(parent: DatabaseErrorParent, options?: ErrorOptions);
class Transaction
class Transaction {}
The transaction object is used to identify a running transaction. It is created by calling
Sequelize.transaction()
.To run a query under a transaction, you should pass the transaction in the options object.
constructor
constructor(sequelize: Sequelize, options: TransactionOptions);
property LOCK
static readonly LOCK: typeof LOCK;
Returns possible options for row locking
property LOCK
readonly LOCK: typeof LOCK;
Same as its static version, but can also be called on instances of transactions to get possible options for row locking directly from the instance.
method afterCommit
afterCommit: (fn: (transaction: this) => void | Promise<void>) => void;
Adds hook that is run after a transaction is committed
method commit
commit: () => Promise<void>;
Commit the transaction
method rollback
rollback: () => Promise<void>;
Rollback (abort) the transaction
class UniqueConstraintError
class UniqueConstraintError extends ValidationError implements CommonErrorProperties {}
Thrown when a unique constraint is violated in the database
constructor
constructor(options: UniqueConstraintErrorOptions);
property fields
readonly fields: Record<string, unknown>;
property original
readonly original: UniqueConstraintErrorParent;
property parent
readonly parent: UniqueConstraintErrorParent;
property sql
readonly sql: string;
class UnknownConstraintError
class UnknownConstraintError extends DatabaseError implements UnknownConstraintErrorOptions {}
Thrown when constraint name is not found in the database
constructor
constructor( options: UnknownConstraintErrorOptions & DatabaseErrorSubclassOptions);
property constraint
constraint: string;
property fields
fields: Record<string, string | number>;
property table
table: string;
class ValidationError
class ValidationError extends BaseError {}
Validation Error. Thrown when the sequelize validation has failed. The error contains an
errors
property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed.Parameter message
Error message
Parameter errors
Array of ValidationErrorItem objects describing the validation errors
constructor
constructor( message: string, errors: ValidationErrorItem[], options?: ErrorOptions);
property errors
readonly errors: ValidationErrorItem[];
Array of ValidationErrorItem objects describing the validation errors
method get
get: (path: string) => ValidationErrorItem[];
Gets all validation error items for the path / field specified.
Parameter path
The path to be checked for error items
Returns
{Array} Validation error items for the specified path
class ValidationErrorItem
class ValidationErrorItem {}
Validation Error Item Instances of this class are included in the
ValidationError.errors
property.
constructor
constructor( message: string, type: | 'notnull violation' | 'string violation' | 'unique violation' | 'validation error' | 'CORE' | 'DB' | 'FUNCTION', path: string, value: string, instance: Model<any, any>, validatorKey: string, fnName: string, fnArgs: unknown[]);
Creates a new ValidationError item. Instances of this class are included in the
ValidationError.errors
property.Parameter message
An error message
Parameter type
The type/origin of the validation error
Parameter path
The field that triggered the validation error
Parameter value
The value that generated the error
Parameter instance
the DAO instance that caused the validation error
Parameter validatorKey
a validation "key", used for identification
Parameter fnName
property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
Parameter fnArgs
parameters used with the BUILT-IN validator function, if applicable
property instance
readonly instance: Model<any, any>;
The DAO instance that caused the validation error
property message
readonly message: string;
An error message
property origin
readonly origin: 'CORE' | 'DB' | 'FUNCTION';
property Origins
static Origins: typeof ValidationErrorItemOrigin;
Deprecated
Will be removed in v7
property path
readonly path: string;
The field that triggered the validation error
property type
readonly type: | 'notnull violation' | 'string violation' | 'unique violation' | 'validation error';
The type/origin of the validation error
property TypeStringMap
static TypeStringMap: typeof ValidationErrorItemType;
Deprecated
Will be removed in v7
property validatorArgs
readonly validatorArgs: unknown[];
Parameters used with the BUILT-IN validator function, if applicable
property validatorKey
readonly validatorKey: string;
A validation "key", used for identification
property validatorName
readonly validatorName: string;
Property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
property value
readonly value: string;
The value that generated the error
method getValidatorKey
getValidatorKey: (useTypeAsNS: boolean, NSSeparator: string) => string;
return a lowercase, trimmed string "key" that identifies the validator.
Note: the string will be empty if the instance has neither a valid
validatorKey
property nor a validvalidatorName
propertyParameter useTypeAsNS
controls whether the returned value is "namespace", this parameter is ignored if the validator's
type
is not one of ValidationErrorItem.OriginsParameter NSSeparator
a separator string for concatenating the namespace, must be not be empty, defaults to "." (fullstop). only used and validated if useTypeAsNS is TRUE.
Throws
{Error} thrown if NSSeparator is found to be invalid.
Interfaces
interface AbstractDataType
interface AbstractDataType {}
property dialectTypes
dialectTypes: string;
property key
key: string;
method stringify
stringify: (value: unknown, options?: object) => string;
method toSql
toSql: () => string;
method toString
toString: (options: object) => string;
interface AbstractDataTypeConstructor
interface AbstractDataTypeConstructor {}
property key
key: string;
method warn
warn: (link: string, text: string) => void;
construct signature
new (): AbstractDataType;
call signature
(): AbstractDataType;
interface AddCheckConstraintOptions
interface AddCheckConstraintOptions extends BaseConstraintOptions {}
interface AddDefaultConstraintOptions
interface AddDefaultConstraintOptions extends BaseConstraintOptions {}
property defaultValue
defaultValue?: unknown;
property type
type: 'default';
interface AddForeignKeyConstraintOptions
interface AddForeignKeyConstraintOptions extends BaseConstraintOptions {}
property deferrable
deferrable?: Deferrable;
property onDelete
onDelete: string;
property onUpdate
onUpdate: string;
property references
references?: { table: TableName; field: string;};
property type
type: 'foreign key';
interface AddPrimaryKeyConstraintOptions
interface AddPrimaryKeyConstraintOptions extends BaseConstraintOptions {}
property deferrable
deferrable?: Deferrable;
property type
type: 'primary key';
interface AddScopeOptions
interface AddScopeOptions {}
AddScope Options for Model.addScope
property override
override: boolean;
If a scope of the same name already exists, should it be overwritten?
interface AddUniqueConstraintOptions
interface AddUniqueConstraintOptions extends BaseConstraintOptions {}
property deferrable
deferrable?: Deferrable;
property type
type: 'unique';
interface AggregateOptions
interface AggregateOptions<T extends DataType | unknown, TAttributes = any> extends QueryOptions, Filterable<TAttributes>, Paranoid {}
Options used for Model.aggregate
interface AllOperator
interface AllOperator {}
Deprecated
unused
property [Op.all]
[Op.all]: readonly (string | number | Date | Literal)[] | Literal;
interface AndOperator
interface AndOperator<TAttributes = any> {}
Example:
[Op.and]: {a: 5}
becomesAND (a = 5)
Deprecated
do not use me!
property [Op.and]
[Op.and]: | WhereOptions<TAttributes> | readonly WhereOptions<TAttributes>[] | WhereValue<TAttributes> | readonly WhereValue<TAttributes>[];
interface AnyOperator
interface AnyOperator {}
Deprecated
unused
property [Op.any]
[Op.any]: readonly (string | number | Date | Literal)[] | Literal;
interface ArrayDataType
interface ArrayDataType<T extends AbstractDataTypeConstructor | AbstractDataType> extends AbstractDataType {}
property options
options: ArrayDataTypeOptions<T>;
interface ArrayDataTypeConstructor
interface ArrayDataTypeConstructor extends AbstractDataTypeConstructor {}
method is
is: <T extends AbstractDataTypeConstructor | AbstractDataType>( obj: unknown, type: T) => obj is ArrayDataType<T>;
construct signature
new <T extends AbstractDataTypeConstructor | AbstractDataType>( type: T): ArrayDataType<T>;
construct signature
new <T extends AbstractDataTypeConstructor | AbstractDataType>( options: ArrayDataTypeOptions<T>): ArrayDataType<T>;
call signature
<T extends AbstractDataTypeConstructor | AbstractDataType>( type: T): ArrayDataType<T>;
call signature
<T extends AbstractDataTypeConstructor | AbstractDataType>( options: ArrayDataTypeOptions<T>): ArrayDataType<T>;
interface ArrayDataTypeOptions
interface ArrayDataTypeOptions< T extends AbstractDataTypeConstructor | AbstractDataType> {}
property type
type: T;
interface AssociationOptions
interface AssociationOptions extends Hookable {}
Options provided when associating models
property as
as?: string | { singular: string; plural: string };
The alias of this model, in singular form. See also the
name
option passed tosequelize.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 assocition, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target
property constraints
constraints?: boolean;
Should on update and on delete constraints be enabled on the foreign key.
property foreignKey
foreignKey?: string | ForeignKeyOptions;
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 aname
property to set the name of the column. Defaults to the name of source + primary key of source
property foreignKeyConstraint
foreignKeyConstraint?: boolean;
property onDelete
onDelete?: string;
What happens when delete occurs.
Cascade if this is a n:m, and set null if it is a 1:m
'SET NULL' or 'CASCADE'
property onUpdate
onUpdate?: string;
What happens when update occurs
'CASCADE'
property scope
scope?: AssociationScope;
interface AssociationScope
interface AssociationScope {}
Options for Association Scope
index signature
[scopeName: string]: unknown;
The name of the column that will be used for the associated scope and it's value
interface BaseConstraintOptions
interface BaseConstraintOptions {}
interface BelongsToCreateAssociationMixinOptions
interface BelongsToCreateAssociationMixinOptions extends CreateOptions<any>, BelongsToSetAssociationMixinOptions {}
The options for the createAssociation mixin of the belongsTo association.
See Also
BelongsToCreateAssociationMixin
interface BelongsToGetAssociationMixinOptions
interface BelongsToGetAssociationMixinOptions extends FindOptions<any> {}
The options for the getAssociation mixin of the belongsTo association.
See Also
BelongsToGetAssociationMixin
property scope
scope?: string | string[] | boolean;
Apply a scope on the related model, or remove its default scope by passing false.
interface BelongsToManyAddAssociationMixinOptions
interface BelongsToManyAddAssociationMixinOptions extends FindOptions<any>, BulkCreateOptions<any>, InstanceUpdateOptions<any>, InstanceDestroyOptions {}
The options for the addAssociation mixin of the belongsToMany association.
See Also
BelongsToManyAddAssociationMixin
property through
through?: JoinTableAttributes;
interface BelongsToManyAddAssociationsMixinOptions
interface BelongsToManyAddAssociationsMixinOptions extends FindOptions<any>, BulkCreateOptions<any>, InstanceUpdateOptions<any>, InstanceDestroyOptions {}
The options for the addAssociations mixin of the belongsToMany association.
See Also
BelongsToManyAddAssociationsMixin
property through
through?: JoinTableAttributes;
interface BelongsToManyCountAssociationsMixinOptions
interface BelongsToManyCountAssociationsMixinOptions extends Transactionable, Filterable<any> {}
The options for the countAssociations mixin of the belongsToMany association.
See Also
BelongsToManyCountAssociationsMixin
property scope
scope?: string | boolean;
Apply a scope on the related model, or remove its default scope by passing false.
interface BelongsToManyCreateAssociationMixinOptions
interface BelongsToManyCreateAssociationMixinOptions extends CreateOptions<any> {}
The options for the createAssociation mixin of the belongsToMany association.
See Also
BelongsToManyCreateAssociationMixin
property through
through?: JoinTableAttributes;
interface BelongsToManyGetAssociationsMixinOptions
interface BelongsToManyGetAssociationsMixinOptions extends FindOptions<any> {}
The options for the getAssociations mixin of the belongsToMany association.
See Also
BelongsToManyGetAssociationsMixin
property joinTableAttributes
joinTableAttributes?: FindAttributeOptions;
A list of the attributes from the join table that you want to select.
property scope
scope?: string | boolean;
Apply a scope on the related model, or remove its default scope by passing false.
interface BelongsToManyHasAssociationMixinOptions
interface BelongsToManyHasAssociationMixinOptions extends BelongsToManyGetAssociationsMixinOptions {}
The options for the hasAssociation mixin of the belongsToMany association.
See Also
BelongsToManyHasAssociationMixin
interface BelongsToManyHasAssociationsMixinOptions
interface BelongsToManyHasAssociationsMixinOptions extends BelongsToManyGetAssociationsMixinOptions {}
The options for the hasAssociations mixin of the belongsToMany association.
See Also
BelongsToManyHasAssociationsMixin
interface BelongsToManyOptions
interface BelongsToManyOptions extends ManyToManyOptions {}
Options provided when associating models with belongsToMany relationship
property otherKey
otherKey?: string | ForeignKeyOptions;
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 aname
property to set the name of the colum. Defaults to the name of target + primary key of target
property sourceKey
sourceKey?: string;
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
property targetKey
targetKey?: string;
The name of the field to use as the key for the association in the target table. Defaults to the primary key of the target table
property through
through: ModelType | string | ThroughOptions;
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.
property timestamps
timestamps?: boolean;
Should the join model have timestamps
property uniqueKey
uniqueKey?: string;
The unique key name to override the autogenerated one when primary key is not present on through model
interface BelongsToManyRemoveAssociationMixinOptions
interface BelongsToManyRemoveAssociationMixinOptions extends InstanceDestroyOptions {}
The options for the removeAssociation mixin of the belongsToMany association.
See Also
BelongsToManyRemoveAssociationMixin
interface BelongsToManyRemoveAssociationsMixinOptions
interface BelongsToManyRemoveAssociationsMixinOptions extends InstanceDestroyOptions, InstanceDestroyOptions {}
The options for the removeAssociations mixin of the belongsToMany association.
See Also
BelongsToManyRemoveAssociationsMixin
interface BelongsToManySetAssociationsMixinOptions
interface BelongsToManySetAssociationsMixinOptions extends FindOptions<any>, BulkCreateOptions<any>, InstanceUpdateOptions<any>, InstanceDestroyOptions {}
The options for the setAssociations mixin of the belongsToMany association.
See Also
BelongsToManySetAssociationsMixin
property through
through?: JoinTableAttributes;
interface BelongsToOptions
interface BelongsToOptions extends AssociationOptions {}
Options provided when associating models with belongsTo relationship
See Also
Association class belongsTo method
interface BelongsToSetAssociationMixinOptions
interface BelongsToSetAssociationMixinOptions extends SaveOptions<any> {}
The options for the setAssociation mixin of the belongsTo association.
See Also
BelongsToSetAssociationMixin
property save
save?: boolean;
Skip saving this after setting the foreign key if false.
interface BigIntDataType
interface BigIntDataType extends NumberDataType {}
property options
options: IntegerDataTypeOptions;
interface BigIntDataTypeConstructor
interface BigIntDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (options?: IntegerDataTypeOptions): BigIntDataType;
call signature
(options?: IntegerDataTypeOptions): BigIntDataType;
interface BlobDataType
interface BlobDataType extends AbstractDataType {}
interface BlobDataTypeConstructor
interface BlobDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (length?: BlobSize): BlobDataType;
construct signature
new (options?: BlobDataTypeOptions): BlobDataType;
call signature
(length?: BlobSize): BlobDataType;
call signature
(options?: BlobDataTypeOptions): BlobDataType;
interface BlobDataTypeOptions
interface BlobDataTypeOptions {}
interface BuildOptions
interface BuildOptions {}
Options for Model.build method
property include
include?: Includeable | Includeable[];
An array of include options. A single option is also supported - Used to build prefetched/included model instances. See
set
TODO: See set
property isNewRecord
isNewRecord?: boolean;
Is this record new
property raw
raw?: boolean;
If set to true, values will ignore field and virtual setters.
interface BulkCreateOptions
interface BulkCreateOptions<TAttributes = any> extends Logging, Transactionable, Hookable, SearchPathable {}
Options for Model.bulkCreate method
property conflictAttributes
conflictAttributes?: Array<keyof TAttributes>;
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
property conflictWhere
conflictWhere?: WhereOptions<TAttributes>;
An optional parameter to specify a where clause for partial unique indexes (note:
ON CONFLICT WHERE
notON CONFLICT DO UPDATE WHERE
). Only supported in Postgres >= 9.5 and sqlite >= 9.5
property fields
fields?: (keyof TAttributes)[];
Fields to insert (defaults to all fields)
property ignoreDuplicates
ignoreDuplicates?: boolean;
Ignore duplicate values for primary keys?
false
property include
include?: Includeable | Includeable[];
Include options. See
find
for details
property individualHooks
individualHooks?: boolean;
Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
property returning
returning?: boolean | (keyof TAttributes)[];
Return all columns or only the specified columns for the affected rows (only for postgres)
property updateOnDuplicate
updateOnDuplicate?: (keyof TAttributes)[];
Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5).
property validate
validate?: boolean;
Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
interface CharDataType
interface CharDataType extends StringDataType {}
property options
options: CharDataTypeOptions;
interface CharDataTypeConstructor
interface CharDataTypeConstructor extends StringDataTypeConstructor {}
construct signature
new (length?: number, binary?: boolean): CharDataType;
construct signature
new (options?: CharDataTypeOptions): CharDataType;
call signature
(length?: number, binary?: boolean): CharDataType;
call signature
(options?: CharDataTypeOptions): CharDataType;
interface CharDataTypeOptions
interface CharDataTypeOptions extends StringDataTypeOptions {}
interface CollateCharsetOptions
interface CollateCharsetOptions {}
interface ColumnDescription
interface ColumnDescription {}
property allowNull
allowNull: boolean;
property autoIncrement
autoIncrement: boolean;
property comment
comment: string | null;
property defaultValue
defaultValue: string;
property primaryKey
primaryKey: boolean;
property type
type: string;
interface ColumnOptions
interface ColumnOptions {}
General column options
property allowNull
allowNull?: boolean;
If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved.
true
property defaultValue
defaultValue?: unknown;
A literal default value, a JavaScript function, or an SQL function (see
sequelize.fn
)
property field
field?: string;
If set, sequelize will map the attribute name to a different name in the database
interface ColumnsDescription
interface ColumnsDescription {}
index signature
[key: string]: ColumnDescription;
interface Config
interface Config {}
Final config options generated by sequelize.
property database
readonly database: string;
property dialectModule
readonly dialectModule?: object;
property dialectModulePath
readonly dialectModulePath: null | string;
property dialectOptions
readonly dialectOptions?: { readonly charset?: string; readonly timeout?: number;};
property host
readonly host?: string;
property keepDefaultTimezone
readonly keepDefaultTimezone?: boolean;
property native
readonly native: boolean;
property password
readonly password: string | null;
property pool
readonly pool?: { readonly acquire: number; readonly idle: number; readonly max: number; readonly min: number;};
property port
readonly port?: string;
property protocol
readonly protocol: 'tcp';
property replication
readonly replication: ReplicationOptions | false;
property ssl
readonly ssl: boolean;
property username
readonly username: string;
interface ConnectionOptions
interface ConnectionOptions {}
interface CountOptions
interface CountOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Projectable, Paranoid, Poolable {}
Options for Model.count method
property col
col?: string;
The column to aggregate on.
property distinct
distinct?: boolean;
Apply COUNT(DISTINCT(col))
property group
group?: GroupOption;
GROUP BY in sql Used in conjunction with
attributes
.See Also
Projectable
property include
include?: Includeable | Includeable[];
Include options. See
find
for details
interface CreateDatabaseOptions
interface CreateDatabaseOptions extends CollateCharsetOptions, QueryOptions {}
property encoding
encoding?: string;
interface CreateOptions
interface CreateOptions<TAttributes = any> extends BuildOptions, Logging, Silent, Transactionable, Hookable {}
Options for Model.create method
property fields
fields?: (keyof TAttributes)[];
If set, only columns matching those in fields will be saved
property ignoreDuplicates
ignoreDuplicates?: boolean;
dialect specific ON CONFLICT DO NOTHING / INSERT IGNORE
property returning
returning?: boolean | (keyof TAttributes)[];
Return the affected rows (only for postgres)
property validate
validate?: boolean;
If false, validations won't be run.
true
interface DateDataType
interface DateDataType extends AbstractDataType {}
property options
options: DateDataTypeOptions;
interface DateDataTypeConstructor
interface DateDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (length?: string | number): DateDataType;
construct signature
new (options?: DateDataTypeOptions): DateDataType;
call signature
(length?: string | number): DateDataType;
call signature
(options?: DateDataTypeOptions): DateDataType;
interface DateDataTypeOptions
interface DateDataTypeOptions {}
property length
length?: string | number;
interface DateOnlyDataType
interface DateOnlyDataType extends AbstractDataType {}
interface DateOnlyDataTypeConstructor
interface DateOnlyDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (): DateOnlyDataType;
call signature
(): DateOnlyDataType;
interface DecimalDataType
interface DecimalDataType extends NumberDataType {}
property options
options: DecimalDataTypeOptions;
interface DecimalDataTypeConstructor
interface DecimalDataTypeConstructor extends NumberDataTypeConstructor {}
property PRECISION
PRECISION: this;
property SCALE
SCALE: this;
construct signature
new (precision?: number, scale?: number): DecimalDataType;
construct signature
new (options?: DecimalDataTypeOptions): DecimalDataType;
call signature
(precision?: number, scale?: number): DecimalDataType;
call signature
(options?: DecimalDataTypeOptions): DecimalDataType;
interface DecimalDataTypeOptions
interface DecimalDataTypeOptions {}
interface DefaultSetOptions
interface DefaultSetOptions {}
interface DestroyOptions
interface DestroyOptions<TAttributes = any> extends TruncateOptions<TAttributes> {}
Options used for Model.destroy
property truncate
truncate?: boolean;
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
interface DoubleDataType
interface DoubleDataType extends NumberDataType {}
property options
options: DoubleDataTypeOptions;
interface DoubleDataTypeConstructor
interface DoubleDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (length?: number, decimals?: number): DoubleDataType;
construct signature
new (options?: DoubleDataTypeOptions): DoubleDataType;
call signature
(length?: number, decimals?: number): DoubleDataType;
call signature
(options?: DoubleDataTypeOptions): DoubleDataType;
interface DoubleDataTypeOptions
interface DoubleDataTypeOptions {}
interface DropOptions
interface DropOptions extends Logging {}
Options to pass to Model on drop
property cascade
cascade?: boolean;
Also drop all objects depending on this table, such as views. Only works in postgres
interface EnumDataType
interface EnumDataType<T extends string> extends AbstractDataType {}
interface EnumDataTypeConstructor
interface EnumDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new <T extends string>(...values: T[]): EnumDataType<T>;
construct signature
new <T extends string>(options: EnumDataTypeOptions<T>): EnumDataType<T>;
call signature
<T extends string>(...values: T[]): EnumDataType<T>;
call signature
<T extends string>(options: EnumDataTypeOptions<T>): EnumDataType<T>;
interface EnumDataTypeOptions
interface EnumDataTypeOptions<T extends string> {}
property values
values: T[];
interface Filterable
interface Filterable<TAttributes = any> {}
property where
where?: WhereOptions<TAttributes>;
Attribute has to be matched for rows to be selected for the given action.
interface FindAndCountOptions
interface FindAndCountOptions<TAttributes = any> extends CountOptions<TAttributes>, FindOptions<TAttributes> {}
interface FindOptions
interface FindOptions<TAttributes = any> extends QueryOptions, Filterable<TAttributes>, Projectable, Paranoid, IndexHintable {}
Options that are passed to any model creating a SELECT query
A hash of options to describe the scope of the search
property group
group?: GroupOption;
GROUP BY in sql
property groupedLimit
groupedLimit?: unknown;
property having
having?: WhereOptions<any>;
Select group rows after groups and aggregates are computed.
property include
include?: Includeable | Includeable[];
A list of associations to eagerly load using a left join (a single association is also supported). Supported is either
{ include: Model1 }
,{ include: [ Model1, Model2, ...]}
,{ include: [{ model: Model1, as: 'Alias' }]}
or{ include: [{ all: true }]}
. If your association are set up with anas
(eg.X.hasMany(Y, { as: 'Z' }
, you need to specify Z in the as attribute when eager loading Y).
property limit
limit?: number;
Limits how many items will be retrieved by the operation.
If
limit
andinclude
are used together, Sequelize will turn thesubQuery
option on by default. This is done to ensure thatlimit
only impacts the Model on the same level as thelimit
option.You can disable this behavior by explicitly setting
subQuery: false
, howeverlimit
will then affect the total count of returned values, including eager-loaded associations, instead of just one table.Example 1
// 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 2
// 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, });
property lock
lock?: LOCK | { level: LOCK; of: ModelStatic<Model> } | boolean;
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 [transaction.LOCK for an example](transaction#lock)
property offset
offset?: number;
Skip the results;
property order
order?: Order;
Specifies an ordering. If a string is provided, it will be escaped. 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.
property raw
raw?: boolean;
Return raw result. See sequelize.query for more information.
property skipLocked
skipLocked?: boolean;
Skip locked rows. Only supported in Postgres.
property subQuery
subQuery?: boolean;
Use sub queries (internal).
If unspecified, this will
true
by default iflimit
is specified, andfalse
otherwise. See FindOptions#limit for more information.
interface FindOrBuildOptions
interface FindOrBuildOptions<TAttributes = any, TCreationAttributes = TAttributes> extends FindOptions<TAttributes>, BuildOptions {}
Options for Model.findOrBuild method
property defaults
defaults?: TCreationAttributes;
Default values to use if building a new instance
interface FindOrCreateOptions
interface FindOrCreateOptions<TAttributes = any, TCreationAttributes = TAttributes> extends FindOptions<TAttributes>, CreateOptions<TAttributes> {}
Options for Model.findOrCreate method
property defaults
defaults?: TCreationAttributes;
Default values to use if building a new instance
interface FloatDataType
interface FloatDataType extends NumberDataType {}
property options
options: FloatDataTypeOptions;
interface FloatDataTypeConstructor
interface FloatDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (length?: number, decimals?: number): FloatDataType;
construct signature
new (options?: FloatDataTypeOptions): FloatDataType;
call signature
(length?: number, decimals?: number): FloatDataType;
call signature
(options?: FloatDataTypeOptions): FloatDataType;
interface FloatDataTypeOptions
interface FloatDataTypeOptions {}
interface ForeignKeyOptions
interface ForeignKeyOptions extends ColumnOptions {}
Foreign Key Options
property name
name?: string;
Attribute name for the relation
interface FunctionParam
interface FunctionParam {}
interface GeographyDataType
interface GeographyDataType extends AbstractDataType {}
interface GeographyDataTypeConstructor
interface GeographyDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (type: string, srid?: number): GeographyDataType;
construct signature
new (options: GeographyDataTypeOptions): GeographyDataType;
call signature
(type: string, srid?: number): GeographyDataType;
call signature
(options: GeographyDataTypeOptions): GeographyDataType;
interface GeographyDataTypeOptions
interface GeographyDataTypeOptions {}
interface GeometryDataType
interface GeometryDataType extends AbstractDataType {}
interface GeometryDataTypeConstructor
interface GeometryDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (type: string, srid?: number): GeometryDataType;
construct signature
new (options: GeometryDataTypeOptions): GeometryDataType;
call signature
(type: string, srid?: number): GeometryDataType;
call signature
(options: GeometryDataTypeOptions): GeometryDataType;
interface GeometryDataTypeOptions
interface GeometryDataTypeOptions {}
interface GroupedCountResultItem
interface GroupedCountResultItem {}
property count
count: number;
index signature
[key: string]: unknown;
interface HasManyAddAssociationMixinOptions
interface HasManyAddAssociationMixinOptions extends InstanceUpdateOptions<any> {}
The options for the addAssociation mixin of the hasMany association.
See Also
HasManyAddAssociationMixin
interface HasManyAddAssociationsMixinOptions
interface HasManyAddAssociationsMixinOptions extends InstanceUpdateOptions<any> {}
The options for the addAssociations mixin of the hasMany association.
See Also
HasManyAddAssociationsMixin
interface HasManyCountAssociationsMixinOptions
interface HasManyCountAssociationsMixinOptions extends Transactionable, Filterable<any> {}
The options for the countAssociations mixin of the hasMany association.
See Also
HasManyCountAssociationsMixin
property scope
scope?: string | boolean;
Apply a scope on the related model, or remove its default scope by passing false.
interface HasManyCreateAssociationMixinOptions
interface HasManyCreateAssociationMixinOptions extends CreateOptions<any> {}
The options for the createAssociation mixin of the hasMany association.
See Also
HasManyCreateAssociationMixin
interface HasManyGetAssociationsMixinOptions
interface HasManyGetAssociationsMixinOptions extends FindOptions<any> {}
The options for the getAssociations mixin of the hasMany association.
See Also
HasManyGetAssociationsMixin
property scope
scope?: string | string[] | boolean;
Apply a scope on the related model, or remove its default scope by passing false.
interface HasManyHasAssociationMixinOptions
interface HasManyHasAssociationMixinOptions extends HasManyGetAssociationsMixinOptions {}
The options for the hasAssociation mixin of the hasMany association.
See Also
HasManyHasAssociationMixin
interface HasManyHasAssociationsMixinOptions
interface HasManyHasAssociationsMixinOptions extends HasManyGetAssociationsMixinOptions {}
The options for the hasAssociations mixin of the hasMany association.
See Also
HasManyHasAssociationsMixin
interface HasManyOptions
interface HasManyOptions extends ManyToManyOptions {}
Options provided when associating models with hasMany relationship
interface HasManyRemoveAssociationMixinOptions
interface HasManyRemoveAssociationMixinOptions extends InstanceUpdateOptions<any> {}
The options for the removeAssociation mixin of the hasMany association.
See Also
HasManyRemoveAssociationMixin
interface HasManyRemoveAssociationsMixinOptions
interface HasManyRemoveAssociationsMixinOptions extends InstanceUpdateOptions<any> {}
The options for the removeAssociations mixin of the hasMany association.
See Also
HasManyRemoveAssociationsMixin
interface HasManySetAssociationsMixinOptions
interface HasManySetAssociationsMixinOptions extends FindOptions<any>, InstanceUpdateOptions<any> {}
The options for the setAssociations mixin of the hasMany association.
See Also
HasManySetAssociationsMixin
interface HasOneCreateAssociationMixinOptions
interface HasOneCreateAssociationMixinOptions extends HasOneSetAssociationMixinOptions, CreateOptions<any> {}
The options for the createAssociation mixin of the hasOne association.
See Also
HasOneCreateAssociationMixin
interface HasOneGetAssociationMixinOptions
interface HasOneGetAssociationMixinOptions extends FindOptions<any> {}
The options for the getAssociation mixin of the hasOne association.
See Also
HasOneGetAssociationMixin
property scope
scope?: string | string[] | boolean;
Apply a scope on the related model, or remove its default scope by passing false.
interface HasOneOptions
interface HasOneOptions extends AssociationOptions {}
Options provided when associating models with hasOne relationship
interface HasOneSetAssociationMixinOptions
interface HasOneSetAssociationMixinOptions extends HasOneGetAssociationMixinOptions, SaveOptions<any> {}
The options for the setAssociation mixin of the hasOne association.
See Also
HasOneSetAssociationMixin
property save
save?: boolean;
Skip saving this after setting the foreign key if false.
interface Hookable
interface Hookable {}
property hooks
hooks?: boolean;
If
false
the applicable hooks will not be called. The default value depends on the context.
interface IncludeOptions
interface IncludeOptions extends Filterable<any>, Projectable, Paranoid {}
Complex include options
property as
as?: string;
The alias of the relation, in case the model you want to eagerly load is aliassed. For
hasOne
/belongsTo
, this should be the singular name, and forhasMany
, it should be the plural
property association
association?: Association | string;
The association you want to eagerly load. (This can be used instead of providing a model/as pair)
property duplicating
duplicating?: boolean;
Mark the include as duplicating, will prevent a subquery from being used.
property include
include?: Includeable[];
Load further nested related models
property limit
limit?: number;
Limit include. Only available when setting
separate
to true.
property model
model?: ModelType;
The model you want to eagerly load
property on
on?: WhereOptions<any>;
Custom
on
clause, overrides default.
property order
order?: Order;
Order include. Only available when setting
separate
to true.
property required
required?: boolean;
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.
property right
right?: boolean;
If true, converts to a right join if dialect support it. Ignored if
include.required
is true.
property separate
separate?: boolean;
Run include in separate queries.
property subQuery
subQuery?: boolean;
Use sub queries. This should only be used if you know for sure the query does not result in a cartesian product.
property through
through?: IncludeThroughOptions;
Through Options
property where
where?: WhereOptions<any>;
Note that this converts the eager load to an inner join, unless you explicitly set
required: false
interface IncludeThroughOptions
interface IncludeThroughOptions extends Filterable<any>, Projectable {}
Through options for Include Options
property as
as?: string;
The alias of the relation, in case the model you want to eagerly load is aliassed. For
hasOne
/belongsTo
, this should be the singular name, and forhasMany
, it should be the plural
property paranoid
paranoid?: boolean;
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.
interface IncrementDecrementOptions
interface IncrementDecrementOptions<TAttributes = any> extends Logging, Transactionable, Silent, SearchPathable, Filterable<TAttributes> {}
Options used for Instance.increment method
interface IncrementDecrementOptionsWithBy
interface IncrementDecrementOptionsWithBy<TAttributes = any> extends IncrementDecrementOptions<TAttributes> {}
Options used for Instance.increment method
property by
by?: number;
The number to increment by
1
interface IndexesOptions
interface IndexesOptions {}
property concurrently
concurrently?: boolean;
PostgreSQL will build the index without taking any write locks. Postgres only
false
property fields
fields?: ( | string | { name: string; length?: number; order?: 'ASC' | 'DESC'; collate?: string; operator?: string; } | Fn | Literal)[];
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:name
(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),operator
(likes IndexesOptions['operator'])
property name
name?: string;
The name of the index. Defaults to model name + _ + fields concatenated
property operator
operator?: string;
Index operator type. Postgres only
property parser
parser?: string | null;
For FULLTEXT columns set your parser
property prefix
prefix?: string;
Prefix to append to the index name.
property type
type?: IndexType;
Index type. Only used by mysql. One of
UNIQUE
,FULLTEXT
andSPATIAL
property unique
unique?: boolean;
Should the index by unique? Can also be triggered by setting type to
UNIQUE
false
property using
using?: IndexMethod;
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, SPGIST, BRIN and GIN.
property where
where?: WhereOptions<any>;
Optional where parameter for index. Can be used to limit the index to certain rows.
interface IndexHint
interface IndexHint {}
interface IndexHintable
interface IndexHintable {}
property indexHints
indexHints?: IndexHint[];
MySQL only.
interface InitOptions
interface InitOptions<M extends Model = Model> extends ModelOptions<M> {}
Options passed to [[Model.init]]
property sequelize
sequelize: Sequelize;
The sequelize connection. Required ATM.
interface InstanceDestroyOptions
interface InstanceDestroyOptions extends Logging, Transactionable, Hookable {}
Options used for Instance.destroy method
property force
force?: boolean;
If set to true, paranoid models will actually be deleted
interface InstanceRestoreOptions
interface InstanceRestoreOptions extends Logging, Transactionable {}
Options used for Instance.restore method
interface InstanceUpdateOptions
interface InstanceUpdateOptions<TAttributes = any> extends SaveOptions<TAttributes>, SetOptions, Filterable<TAttributes> {}
Options used for Instance.update method
interface IntegerDataType
interface IntegerDataType extends NumberDataType {}
property options
options: NumberDataTypeOptions;
interface IntegerDataTypeConstructor
interface IntegerDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (options?: NumberDataTypeOptions): IntegerDataType;
call signature
(options?: NumberDataTypeOptions): IntegerDataType;
interface IntegerDataTypeOptions
interface IntegerDataTypeOptions {}
interface JoinTableAttributes
interface JoinTableAttributes {}
Attributes for the join table
index signature
[attribute: string]: unknown;
interface Logging
interface Logging {}
interface ManyToManyOptions
interface ManyToManyOptions extends AssociationOptions {}
Options provided for many-to-many relationships
property scope
scope?: AssociationScope;
A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
interface MediumIntegerDataType
interface MediumIntegerDataType extends NumberDataType {}
property options
options: IntegerDataTypeOptions;
interface MediumIntegerDataTypeConstructor
interface MediumIntegerDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (options?: IntegerDataTypeOptions): MediumIntegerDataType;
call signature
(options?: IntegerDataTypeOptions): MediumIntegerDataType;
interface ModelAttributeColumnOptions
interface ModelAttributeColumnOptions<M extends Model = Model> extends ColumnOptions {}
Column options for the model schema attributes
property autoIncrement
autoIncrement?: boolean;
Is this field an auto increment field
property autoIncrementIdentity
autoIncrementIdentity?: boolean;
If this field is a Postgres auto increment field, use Postgres
GENERATED BY DEFAULT AS IDENTITY
instead ofSERIAL
. Postgres 10+ only.
property comment
comment?: string;
Comment for the database
property onDelete
onDelete?: string;
What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
property onUpdate
onUpdate?: string;
What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
property primaryKey
primaryKey?: boolean;
Primary key flag
property references
references?: string | ModelAttributeColumnReferencesOptions;
An object with reference configurations or the column name as string
property type
type: DataType;
A string or a data type
property unique
unique?: boolean | string | { name: string; msg: string };
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
property validate
validate?: ModelValidateOptions;
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 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, it it is async, the callback should be called with the error text.
property values
values?: readonly string[];
Usage in object notation
class MyModel extends Model {}MyModel.init({states: {type: Sequelize.ENUM,values: ['active', 'pending', 'deleted']}}, { sequelize })
method get
get: (this: M) => unknown;
Provide a custom getter for this column. Use
this.getDataValue(String)
to manipulate the underlying values.
method set
set: (this: M, val: unknown) => void;
Provide a custom setter for this column. Use
this.setDataValue(String, Value)
to manipulate the underlying values.
interface ModelAttributeColumnReferencesOptions
interface ModelAttributeColumnReferencesOptions {}
References options for the column's attributes
property deferrable
deferrable?: Deferrable;
When to check for the foreign key constraing
PostgreSQL only
property key
key?: string;
The column of the foreign table that this column references
property model
model?: TableName | ModelType;
If this column references another table, provide it here as a Model, or a string
interface ModelGetterOptions
interface ModelGetterOptions<M extends Model = Model> {}
Interface for getterMethods in InitOptions
index signature
[name: string]: (this: M) => unknown;
interface ModelNameOptions
interface ModelNameOptions {}
Interface for name property in InitOptions
interface ModelOptions
interface ModelOptions<M extends Model = Model> {}
Options for model definition
property charset
charset?: string;
property collate
collate?: string;
property comment
comment?: string;
Finaly you can specify a comment for the table in MySQL and PG
property createdAt
createdAt?: string | boolean;
Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting.
property defaultScope
defaultScope?: FindOptions<Attributes<M>>;
Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll.
property deletedAt
deletedAt?: string | boolean;
Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting.
property engine
engine?: string;
You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
property freezeTableName
freezeTableName?: boolean;
If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the dao name will be pluralized. Default false.
property getterMethods
getterMethods?: ModelGetterOptions<M>;
Allows defining additional getters that will be available on model instances.
property hasTrigger
hasTrigger?: boolean;
Indicates if the model's table has a trigger associated with it. Default false.
property hooks
hooks?: Partial<ModelHooks<M, Attributes<M>>>;
An object of hook function that are called before and after certain lifecycle events. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.
property indexes
indexes?: readonly ModelIndexesOptions[];
Indexes for the provided database table
property initialAutoIncrement
initialAutoIncrement?: string;
Set the initial AUTO_INCREMENT value for the table in MySQL.
property modelName
modelName?: string;
Set name of the model. By default its same as Class name.
property name
name?: ModelNameOptions;
An object with two attributes,
singular
andplural
, which are used when this model is associated to others.
property omitNull
omitNull?: boolean;
Don't persits null values. This means that all columns with null values will not be saved.
property paranoid
paranoid?: boolean;
Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs timestamps=true to work. Default false.
property schema
schema?: string;
property scopes
scopes?: ModelScopeOptions<Attributes<M>>;
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
property setterMethods
setterMethods?: ModelSetterOptions<M>;
Allows defining additional setters that will be available on model instances.
property tableName
tableName?: string;
pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim
property timestamps
timestamps?: boolean;
Adds createdAt and updatedAt timestamps to the model. Default true.
property underscored
underscored?: boolean;
Converts all camelCased columns to underscored if true. Default false.
property updatedAt
updatedAt?: string | boolean;
Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. Not affected by underscored setting.
property validate
validate?: ModelValidateOptions;
An object of model wide validations. Validations have access to all model values via
this
. If the validator function takes an argument, it is asumed to be async, and is called with a callback that accepts an optional error.
property version
version?: boolean | string;
Enable optimistic locking. When enabled, sequelize will add a version count attribute to the model and throw an OptimisticLockingError error when stale instances are saved. - If string: Uses the named attribute. - If boolean: Uses
version
.false
property whereMergeStrategy
whereMergeStrategy?: 'and' | 'overwrite';
Specify the scopes merging strategy (default 'overwrite'). Valid values are 'and' and 'overwrite'. When the 'and' strategy is set, scopes will be grouped using the Op.and operator. For instance merging scopes containing
{ where: { myField: 1 }}
and{ where: { myField: 2 }}
will result in{ where: { [Op.and]: [{ myField: 1 }, { myField: 2 }] } }
. When the 'overwrite' strategy is set, scopes containing the same attribute in a where clause will be overwritten by the lastly defined one. For instance merging scopes containing{ where: { myField: 1 }}
and{ where: { myField: 2 }}
will result in{ where: { myField: 2 } }
.false
interface ModelScopeOptions
interface ModelScopeOptions<TAttributes = any> {}
Interface for Define Scope Options
index signature
[scopeName: string]: | FindOptions<TAttributes> | ((...args: readonly any[]) => FindOptions<TAttributes>);
Name of the scope and it's query
interface ModelSetterOptions
interface ModelSetterOptions<M extends Model = Model> {}
Interface for setterMethods in InitOptions
index signature
[name: string]: (this: M, val: any) => void;
interface ModelValidateOptions
interface ModelValidateOptions {}
Model validations, allow you to specify format/content/inheritance validations for each attribute of the model.
Validations are automatically run on create, update and save. You can also call validate() to manually validate an instance.
The validations are implemented by validator.js.
property contains
contains?: string | { msg: string };
force specific substrings
property equals
equals?: string | { msg: string };
only allow a specific value
property is
is?: | string | readonly (string | RegExp)[] | RegExp | { msg: string; args: string | readonly (string | RegExp)[] | RegExp };
-
{ is: ['^[a-z]+$','i'] }
will only allow letters -{ is: /^[a-z]+$/i }
also only allows letters
property isAfter
isAfter?: string | { msg: string; args: string };
only allow date strings after a specific date
property isAlpha
isAlpha?: boolean | { msg: string };
will only allow letters
property isAlphanumeric
isAlphanumeric?: boolean | { msg: string };
will only allow alphanumeric characters, so "_abc" will fail
property isArray
isArray?: boolean | { msg: string; args: boolean };
only allow arrays
property isBefore
isBefore?: string | { msg: string; args: string };
only allow date strings before a specific date
property isCreditCard
isCreditCard?: boolean | { msg: string; args: boolean };
check for valid credit card numbers
property isDate
isDate?: boolean | { msg: string; args: boolean };
only allow date strings
property isDecimal
isDecimal?: boolean | { msg: string };
checks for any numbers
property isEmail
isEmail?: boolean | { msg: string };
checks for email format (foo@bar.com)
property isFloat
isFloat?: boolean | { msg: string };
checks for valid floating point numbers
property isIn
isIn?: | ReadonlyArray<readonly any[]> | { msg: string; args: ReadonlyArray<readonly any[]> };
check the value is one of these
property isInt
isInt?: boolean | { msg: string };
checks for valid integers
property isIP
isIP?: boolean | { msg: string };
checks for IPv4 (129.89.23.1) or IPv6 format
property isIPv4
isIPv4?: boolean | { msg: string };
checks for IPv4 (129.89.23.1)
property isIPv6
isIPv6?: boolean | { msg: string };
checks for IPv6 format
property isLowercase
isLowercase?: boolean | { msg: string };
checks for lowercase
property isNull
isNull?: boolean | { msg: string };
only allows null
property isNumeric
isNumeric?: boolean | { msg: string };
will only allow numbers
property isUppercase
isUppercase?: boolean | { msg: string };
checks for uppercase
property isUrl
isUrl?: boolean | { msg: string };
checks for url format (http://foo.com)
property isUUID
isUUID?: number | { msg: string; args: number };
only allow uuids
property len
len?: | readonly [number, number] | { msg: string; args: readonly [number, number] };
only allow values with length between 2 and 10
property max
max?: number | { msg: string; args: readonly [number] };
only allow values
property min
min?: number | { msg: string; args: readonly [number] };
only allow values >= 23
property not
not?: | string | readonly (string | RegExp)[] | RegExp | { msg: string; args: string | readonly (string | RegExp)[] | RegExp };
-
{ not: ['[a-z]','i'] }
will not allow letters
property notContains
notContains?: | readonly string[] | string | { msg: string; args: readonly string[] | string };
don't allow specific substrings
property notEmpty
notEmpty?: boolean | { msg: string };
don't allow empty strings
property notIn
notIn?: | ReadonlyArray<readonly any[]> | { msg: string; args: ReadonlyArray<readonly any[]> };
check the value is not one of these
property notNull
notNull?: boolean | { msg: string };
won't allow null
index signature
[name: string]: unknown;
Custom validations are also possible
interface MultiAssociationAccessors
interface MultiAssociationAccessors {}
property add
add: string;
property addMultiple
addMultiple: string;
property count
count: string;
property create
create: string;
property get
get: string;
property hasAll
hasAll: string;
property hasSingle
hasSingle: string;
property remove
remove: string;
property removeMultiple
removeMultiple: string;
property set
set: string;
interface NonNullFindOptions
interface NonNullFindOptions<TAttributes = any> extends FindOptions<TAttributes> {}
property rejectOnEmpty
rejectOnEmpty: boolean | Error;
Throw if nothing was found.
interface NumberDataType
interface NumberDataType extends AbstractDataType {}
interface NumberDataTypeConstructor
interface NumberDataTypeConstructor extends AbstractDataTypeConstructor {}
property options
options: NumberDataTypeOptions;
property UNSIGNED
UNSIGNED: this;
property ZEROFILL
ZEROFILL: this;
method validate
validate: (value: unknown) => boolean;
construct signature
new (options?: NumberDataTypeOptions): NumberDataType;
call signature
(options?: NumberDataTypeOptions): NumberDataType;
interface NumberDataTypeOptions
interface NumberDataTypeOptions extends IntegerDataTypeOptions {}
interface OperatorsAliases
interface OperatorsAliases {}
Used to map operators to their Symbol representations
index signature
[K: string]: symbol;
interface Options
interface Options extends Logging {}
Options for the constructor of Sequelize main class
property attributeBehavior
attributeBehavior?: 'escape' | 'throw' | 'unsafe-legacy';
Sequelize had to introduce a breaking change to fix vulnerability CVE-2023-22578. This option allows you to revert to the old behavior (unsafe-legacy), or to opt in to the new behavior (escape). The default behavior throws an error to warn you about the change (throw).
property clientMinMessages
clientMinMessages?: string | boolean;
The PostgreSQL
client_min_messages
session parameter. Set tofalse
to not override the database's default.Deprecated in v7, please use the sequelize option "dialectOptions.clientMinMessages" instead
Deprecated
'warning'
property database
database?: string;
The name of the database
property define
define?: ModelOptions;
Default options for model definitions. See Model.init.
property dialect
dialect?: Dialect;
The dialect of the database you are connecting to. One of mysql, postgres, sqlite, mariadb and mssql.
'mysql'
property dialectModule
dialectModule?: object;
If specified, will use the provided module as the dialect.
Example 1
dialectModule: require('@myorg/tedious'),
property dialectModulePath
dialectModulePath?: string;
If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
property dialectOptions
dialectOptions?: object;
An object of additional options, which are passed directly to the connection library
property hooks
hooks?: Partial<SequelizeHooks<Model, any, any>>;
Sets global permanent hooks.
property host
host?: string;
The host of the relational database.
'localhost'
property isolationLevel
isolationLevel?: string;
Set the default transaction isolation level. See
Sequelize.Transaction.ISOLATION_LEVELS
for possible options.'REPEATABLE_READ'
property logQueryParameters
logQueryParameters?: boolean;
Set to
true
to show bind parameters in log.false
property minifyAliases
minifyAliases?: boolean;
Set to
true
to automatically minify aliases generated by sequelize. Mostly useful to circumvent the POSTGRES alias limit of 64 characters.false
property native
native?: boolean;
A flag that defines if native library shall be used or not. Currently only has an effect for postgres
false
property omitNull
omitNull?: boolean;
A flag that defines if null values should be passed to SQL queries or not.
false
property operatorsAliases
operatorsAliases?: OperatorsAliases;
Sets available operator aliases. See (https://sequelize.org/master/manual/querying.html#operators) for more information. WARNING: Setting this to boolean value was deprecated and is no-op.
all aliases
property password
password?: string;
The password which is used to authenticate against the database.
property pool
pool?: PoolOptions;
Connection pool options
property port
port?: number;
The port of the relational database.
property protocol
protocol?: string;
The protocol of the relational database.
'tcp'
property query
query?: QueryOptions;
Default options for sequelize.query
property quoteIdentifiers
quoteIdentifiers?: boolean;
Set to
false
to make table names and attributes case-insensitive on Postgres and skip double quoting of them.true
property replication
replication?: ReplicationOptions | false;
Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties:
host
,port
,username
,password
,database
false
property retry
retry?: RetryOptions;
property schema
schema?: string;
If defined the connection will use the provided schema instead of the default ("public").
property set
set?: DefaultSetOptions;
Default options for sequelize.set
property ssl
ssl?: boolean;
A flag that defines if is used SSL.
property standardConformingStrings
standardConformingStrings?: boolean;
The PostgreSQL
standard_conforming_strings
session parameter. Set tofalse
to not set the option. WARNING: Setting this to false may expose vulnerabilities and is not recommended!true
property storage
storage?: string;
Only used by sqlite.
':memory:'
property sync
sync?: SyncOptions;
Default options for sequelize.sync
property timezone
timezone?: string;
The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
'+00:00'
property transactionType
transactionType?: Transaction.TYPES;
Set the default transaction type. See Sequelize.Transaction.TYPES for possible options. Sqlite only.
'DEFERRED'
property typeValidation
typeValidation?: boolean;
Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
false
property username
username?: string;
The username which is used to authenticate against the database.
interface OrOperator
interface OrOperator<TAttributes = any> {}
Example:
[Op.or]: [{a: 5}, {a: 6}]
becomes(a = 5 OR a = 6)
Deprecated
do not use me!
property [Op.or]
[Op.or]: | WhereOptions<TAttributes> | readonly WhereOptions<TAttributes>[] | WhereValue<TAttributes> | readonly WhereValue<TAttributes>[];
interface Paranoid
interface Paranoid {}
property paranoid
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
options.paranoid
is true for the model.
interface Poolable
interface Poolable {}
property useMaster
useMaster?: boolean;
Force the query to use the write pool, regardless of the query type.
false
interface PoolOptions
interface PoolOptions {}
Connection Pool options
property acquire
acquire?: number;
The maximum time, in milliseconds, that pool will try to get connection before throwing error
property evict
evict?: number;
The time interval, in milliseconds, after which sequelize-pool will remove idle connections.
property idle
idle?: number;
The maximum time, in milliseconds, that a connection can be idle before being released
property max
max?: number;
Maximum number of connections in pool. Default is 5
property maxUses
maxUses?: number;
The number of times to use a connection before closing and replacing it. Default is Infinity
property min
min?: number;
Minimum number of connections in pool. Default is 0
method validate
validate: (client?: unknown) => boolean;
A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
interface Projectable
interface Projectable {}
property attributes
attributes?: FindAttributeOptions;
A list of the attributes that you want to select. 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
interface QueryInterfaceCreateTableOptions
interface QueryInterfaceCreateTableOptions extends QueryInterfaceOptions, CollateCharsetOptions {}
property engine
engine?: string;
property uniqueKeys
uniqueKeys?: { [keyName: string]: { fields: string[]; customIndex?: boolean; };};
Used for compound unique keys.
interface QueryInterfaceDropAllTablesOptions
interface QueryInterfaceDropAllTablesOptions extends QueryInterfaceOptions {}
property skip
skip?: string[];
interface QueryInterfaceDropTableOptions
interface QueryInterfaceDropTableOptions extends QueryInterfaceOptions {}
interface QueryInterfaceIndexOptions
interface QueryInterfaceIndexOptions extends IndexesOptions, QueryInterfaceOptions {}
interface QueryInterfaceOptions
interface QueryInterfaceOptions extends Logging, Transactionable {}
Most of the methods accept options and use only the logger property of the options. That's why the most used interface type for options in a method is separated here as another interface.
interface QueryOptions
interface QueryOptions extends Logging, Transactionable, Poolable {}
Interface for query options
property bind
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.
property fieldMap
fieldMap?: FieldMap;
Map returned fields to arbitrary names for SELECT query type if
options.fieldMaps
is present.
property instance
instance?: Model;
A sequelize instance used to build the return instance
property mapToModel
mapToModel?: boolean;
Map returned fields to model's fields if
options.model
oroptions.instance
is present. Mapping will occur before building the model instance.
property nest
nest?: boolean;
If true, transforms objects with
.
separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. Whennest
is true, the query type is assumed to be'SELECT'
, unless otherwise specifiedfalse
property plain
plain?: boolean;
Sets the query type to
SELECT
and return a single row
property raw
raw?: boolean;
If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
property replacements
replacements?: BindOrReplacements;
Either an object of named parameter replacements in the format
:param
or an array of unnamed replacements to replace?
in your SQL.
property retry
retry?: RetryOptions;
property type
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.
interface QueryOptionsTransactionRequired
interface QueryOptionsTransactionRequired {}
interface QueryOptionsWithForce
interface QueryOptionsWithForce extends QueryOptions {}
property force
force?: boolean;
interface QueryOptionsWithModel
interface QueryOptionsWithModel<M extends Model> extends QueryOptions {}
property model
model: ModelStatic<M>;
A sequelize model used to build the returned model instances (used to be called callee)
interface QueryOptionsWithType
interface QueryOptionsWithType<T extends QueryTypes> extends QueryOptions {}
property type
type: T;
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.
interface QueryOptionsWithWhere
interface QueryOptionsWithWhere extends QueryOptions, Filterable<any> {}
interface RangeDataType
interface RangeDataType<T extends RangeableDataType> extends AbstractDataType {}
property options
options: RangeDataTypeOptions<T>;
interface RangeDataTypeConstructor
interface RangeDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new <T extends RangeableDataType>(subtype?: T): RangeDataType<T>;
construct signature
new <T extends RangeableDataType>( options: RangeDataTypeOptions<T>): RangeDataType<T>;
call signature
<T extends RangeableDataType>(subtype?: T): RangeDataType<T>;
call signature
<T extends RangeableDataType>( options: RangeDataTypeOptions<T>): RangeDataType<T>;
interface RangeDataTypeOptions
interface RangeDataTypeOptions<T extends RangeableDataType> {}
property subtype
subtype?: T;
interface RealDataType
interface RealDataType extends NumberDataType {}
property options
options: RealDataTypeOptions;
interface RealDataTypeConstructor
interface RealDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (length?: number, decimals?: number): RealDataType;
construct signature
new (options?: RealDataTypeOptions): RealDataType;
call signature
(length?: number, decimals?: number): RealDataType;
call signature
(options?: RealDataTypeOptions): RealDataType;
interface RealDataTypeOptions
interface RealDataTypeOptions {}
interface ReplicationOptions
interface ReplicationOptions {}
Interface for replication Options in the sequelize constructor
interface RestoreOptions
interface RestoreOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Hookable {}
Options for Model.restore
property individualHooks
individualHooks?: boolean;
If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row
property limit
limit?: number;
How many rows to undelete
interface SaveOptions
interface SaveOptions<TAttributes = any> extends Logging, Transactionable, Silent, Hookable {}
Options used for Instance.save method
property fields
fields?: (keyof TAttributes)[];
An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
property omitNull
omitNull?: boolean;
A flag that defines if null values should be passed as values or not.
false
property returning
returning?: boolean | Array<keyof TAttributes>;
Return the affected rows (only for postgres)
property validate
validate?: boolean;
If false, validations won't be run.
true
interface SchemaOptions
interface SchemaOptions extends Logging {}
Schema Options provided for applying a schema to a model
property schemaDelimiter
schemaDelimiter?: string;
The character(s) that separates the schema name from the table name
interface ScopeOptions
interface ScopeOptions {}
Scope Options for Model.scope
property method
method: string | readonly [string, ...unknown[]];
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.
interface SearchPathable
interface SearchPathable {}
property searchPath
searchPath?: string;
An optional parameter to specify the schema search_path (Postgres only)
interface SetOptions
interface SetOptions {}
Options used for Instance.set method
interface Silent
interface Silent {}
property silent
silent?: boolean;
If true, the updatedAt timestamp will not be updated.
false
interface SingleAssociationAccessors
interface SingleAssociationAccessors {}
interface SmallIntegerDataType
interface SmallIntegerDataType extends NumberDataType {}
property options
options: IntegerDataTypeOptions;
interface SmallIntegerDataTypeConstructor
interface SmallIntegerDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (options?: IntegerDataTypeOptions): SmallIntegerDataType;
call signature
(options?: IntegerDataTypeOptions): SmallIntegerDataType;
interface StringDataType
interface StringDataType extends AbstractDataType {}
interface StringDataTypeConstructor
interface StringDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (length?: number, binary?: boolean): StringDataType;
construct signature
new (options?: StringDataTypeOptions): StringDataType;
call signature
(length?: number, binary?: boolean): StringDataType;
call signature
(options?: StringDataTypeOptions): StringDataType;
interface StringDataTypeOptions
interface StringDataTypeOptions {}
interface SyncAlterOptions
interface SyncAlterOptions {}
Additional options for table altering during sync
property drop
drop?: boolean;
Prevents any drop statements while altering a table when set to
false
interface SyncOptions
interface SyncOptions extends Logging, Hookable {}
Sync Options
property alter
alter?: boolean | SyncAlterOptions;
If alter is true, each DAO will do ALTER TABLE ... CHANGE ... Alters tables to fit models. Provide an object for additional configuration. Not recommended for production use. If not further configured deletes data in columns that were removed or had their type changed in the model.
property force
force?: boolean;
If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table
property match
match?: RegExp;
Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
property schema
schema?: string;
The schema that the tables should be created in. This can be overridden for each table in sequelize.define
property searchPath
searchPath?: string;
An optional parameter to specify the schema search_path (Postgres only)
interface TableNameWithSchema
interface TableNameWithSchema {}
interface TextDataType
interface TextDataType extends AbstractDataType {}
interface TextDataTypeConstructor
interface TextDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new (length?: TextLength): TextDataType;
construct signature
new (options?: TextDataTypeOptions): TextDataType;
call signature
(length?: TextLength): TextDataType;
call signature
(options?: TextDataTypeOptions): TextDataType;
interface TextDataTypeOptions
interface TextDataTypeOptions {}
property length
length?: TextLength;
interface ThroughOptions
interface ThroughOptions {}
Used for a association table in n:m associations.
property model
model: ModelType | string;
The model used to join both sides of the N:M association. Can be a string if you want the model to be generated by sequelize.
property paranoid
paranoid?: boolean;
If true the generated join table will be paranoid false
property scope
scope?: AssociationScope;
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)
property unique
unique?: boolean;
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)
true
interface TinyIntegerDataType
interface TinyIntegerDataType extends NumberDataType {}
property options
options: IntegerDataTypeOptions;
interface TinyIntegerDataTypeConstructor
interface TinyIntegerDataTypeConstructor extends NumberDataTypeConstructor {}
construct signature
new (options?: IntegerDataTypeOptions): TinyIntegerDataType;
call signature
(options?: IntegerDataTypeOptions): TinyIntegerDataType;
interface Transactionable
interface Transactionable {}
property transaction
transaction?: Transaction | null;
Transaction to run query under
interface TransactionOptions
interface TransactionOptions extends Logging {}
Options provided when the transaction is created
property autocommit
autocommit?: boolean;
property deferrable
deferrable?: string | Deferrable;
property isolationLevel
isolationLevel?: Transaction.ISOLATION_LEVELS;
property readOnly
readOnly?: boolean;
property transaction
transaction?: Transaction | null;
Parent transaction.
property type
type?: Transaction.TYPES;
interface TruncateOptions
interface TruncateOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Hookable {}
The options passed to Model.destroy in addition to truncate
property cascade
cascade?: boolean;
Only used in conjuction 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.
false;
property force
force?: boolean;
Delete instead of setting deletedAt to current timestamp (only applicable if
paranoid
is enabled)
property individualHooks
individualHooks?: boolean;
If set to true, destroy will SELECT all records matching the where parameter and will execute before / after destroy hooks on each row
property limit
limit?: number;
How many rows to delete
property restartIdentity
restartIdentity?: boolean;
Only used in conjunction with
truncate
. Automatically restart sequences owned by columns of the truncated table
interface UpdateOptions
interface UpdateOptions<TAttributes = any> extends Logging, Transactionable, Paranoid, Hookable {}
Options used for Model.update
property fields
fields?: (keyof TAttributes)[];
Fields to update (defaults to all fields)
property individualHooks
individualHooks?: boolean;
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
false
property limit
limit?: number;
How many rows to update (only for mysql and mariadb)
property returning
returning?: boolean | (keyof TAttributes)[];
Return the affected rows (only for postgres)
property sideEffects
sideEffects?: boolean;
Whether or not to update the side effects of any virtual setters.
true
property silent
silent?: boolean;
If true, the updatedAt timestamp will not be updated.
property validate
validate?: boolean;
Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation.
true
property where
where: WhereOptions<TAttributes>;
Options to describe the scope of the search.
interface UpsertOptions
interface UpsertOptions<TAttributes = any> extends Logging, Transactionable, SearchPathable, Hookable {}
Options for Model.upsert method
property conflictFields
conflictFields?: (keyof TAttributes)[];
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
property conflictWhere
conflictWhere?: WhereOptions<TAttributes>;
An optional parameter that specifies a where clause for the
ON CONFLICT
part of the query (in particular: for applying to partial unique indexes). Only supported in Postgres >= 9.5 and SQLite >= 3.24.0
property fields
fields?: (keyof TAttributes)[];
The fields to insert / update. Defaults to all fields
property returning
returning?: boolean | (keyof TAttributes)[];
Return the affected rows (only for postgres)
property validate
validate?: boolean;
Run validations before the row is inserted
interface Validator
interface Validator extends OrigValidator, Extensions {}
method contains
contains: (str: string, elem: string[]) => boolean;
interface VirtualDataType
interface VirtualDataType<T extends AbstractDataTypeConstructor | AbstractDataType> extends AbstractDataType {}
property fields
fields: string[];
property returnType
returnType: T;
interface VirtualDataTypeConstructor
interface VirtualDataTypeConstructor extends AbstractDataTypeConstructor {}
construct signature
new <T extends AbstractDataTypeConstructor | AbstractDataType>( ReturnType: T, fields?: string[]): VirtualDataType<T>;
call signature
<T extends AbstractDataTypeConstructor | AbstractDataType>( ReturnType: T, fields?: string[]): VirtualDataType<T>;
interface WhereGeometryOptions
interface WhereGeometryOptions {}
Where Geometry Options
property coordinates
coordinates: readonly (number[] | number)[];
property type
type: string;
interface WhereOperators
interface WhereOperators<AttributeType = any> {}
Operators that can be used in WhereOptions
property [Op.adjacent]
[Op.adjacent]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
PG only
Whether the two ranges are adjacent.
@example:
{ rangeAttribute: { [Op.adjacent]: [1, 2] } }// results in// "rangeAttribute" -|- [1, 2)https://www.postgresql.org/docs/14/functions-range.html
property [Op.between]
[Op.between]?: | [ lowerInclusive: OperatorValues<NonNullable<AttributeType>>, higherInclusive: OperatorValues<NonNullable<AttributeType>> ] | Literal;
@example:
[Op.between]: [6, 10],
becomesBETWEEN 6 AND 10
property [Op.contained]
[Op.contained]?: AttributeType extends any[] ? // ARRAY <@ ARRAY ; RANGE <@ RANGE WhereOperators<AttributeType>[typeof Op.overlap] : // ELEMENT <@ RANGE AllowAnyAll<OperatorValues<Rangable<AttributeType>>>;
PG array & range 'contained by' operator
@example:
[Op.contained]: [1, 2]
becomes<@ [1, 2]
property [Op.contains]
[Op.contains]?: // RANGE @> ELEMENTAttributeType extends Range<infer RangeType> ? OperatorValues<OperatorValues<NonNullable<RangeType>>> : | never // ARRAY @> ARRAY ; RANGE @> RANGE | WhereOperators<AttributeType>[typeof Op.overlap];
PG array & range 'contains' operator
@example:
[Op.contains]: [1, 2]
becomes@> [1, 2]
property [Op.endsWith]
[Op.endsWith]?: WhereOperators<AttributeType>[typeof Op.startsWith];
String ends with value.
property [Op.eq]
[Op.eq]?: AllowAnyAll<OperatorValues<AttributeType>>;
@example:
[Op.eq]: 6,
becomes= 6
@example:[Op.eq]: [6, 7]
becomes= ARRAY[6, 7]
@example:[Op.eq]: null
becomesIS NULL
@example:[Op.eq]: true
becomes= true
@example:[Op.eq]: literal('raw sql')
becomes= raw sql
@example:[Op.eq]: col('column')
becomes= "column"
@example:[Op.eq]: fn('NOW')
becomes= NOW()
property [Op.gt]
[Op.gt]?: WhereOperators<AttributeType>[typeof Op.gte];
@example:
[Op.gt]: 6
becomes> 6
property [Op.gte]
[Op.gte]?: AllowAnyAll<OperatorValues<NonNullable<AttributeType>>>;
@example:
[Op.gte]: 6
becomes>= 6
property [Op.iLike]
[Op.iLike]?: WhereOperators<AttributeType>[typeof Op.like];
case insensitive PG only
@example:
[Op.iLike]: '%hat'
becomesILIKE '%hat'
@example:[Op.iLike]: { [Op.any]: ['cat', 'hat']}
becomesILIKE ANY ARRAY['cat', 'hat']
property [Op.in]
[Op.in]?: ReadonlyArray<OperatorValues<NonNullable<AttributeType>>> | Literal;
@example:
[Op.in]: [1, 2],
becomesIN (1, 2)
property [Op.iRegexp]
[Op.iRegexp]?: WhereOperators<AttributeType>[typeof Op.regexp];
PG only
Matches regular expression, case insensitive
@example:
[Op.iRegexp]: '^[h|a|t]'
becomes~* '^[h|a|t]'
property [Op.is]
[Op.is]?: Extract<AttributeType, null | boolean> | Literal;
@example:
[Op.is]: null
becomesIS NULL
@example:[Op.is]: true
becomesIS TRUE
@example:[Op.is]: literal('value')
becomesIS value
property [Op.like]
[Op.like]?: AllowAnyAll<OperatorValues<Extract<AttributeType, string>>>;
@example:
[Op.like]: '%hat',
becomesLIKE '%hat'
@example:[Op.like]: { [Op.any]: ['cat', 'hat'] }
becomesLIKE ANY ARRAY['cat', 'hat']
property [Op.lt]
[Op.lt]?: WhereOperators<AttributeType>[typeof Op.gte];
@example:
[Op.lt]: 10
becomes< 10
property [Op.lte]
[Op.lte]?: WhereOperators<AttributeType>[typeof Op.gte];
@example:
[Op.lte]: 10
becomes<= 10
property [Op.match]
[Op.match]?: AllowAnyAll<DynamicValues<AttributeType>>;
@example:
[Op.match]: Sequelize.fn('to_tsquery', 'fat & rat')
becomes@@ to_tsquery('fat & rat')
property [Op.ne]
[Op.ne]?: WhereOperators<AttributeType>[typeof Op.eq];
@example:
[Op.ne]: 20,
becomes!= 20
@example:[Op.ne]: [20, 21]
becomes!= ARRAY[20, 21]
@example:[Op.ne]: null
becomesIS NOT NULL
@example:[Op.ne]: true
becomes!= true
@example:[Op.ne]: literal('raw sql')
becomes!= raw sql
@example:[Op.ne]: col('column')
becomes!= "column"
@example:[Op.ne]: fn('NOW')
becomes!= NOW()
property [Op.noExtendLeft]
[Op.noExtendLeft]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
PG only
Whether the range extends to the left of the other range.
@example:
{ rangeAttribute: { [Op.noExtendLeft]: [1, 2] } }// results in// "rangeAttribute" &> [1, 2)https://www.postgresql.org/docs/14/functions-range.html
property [Op.noExtendRight]
[Op.noExtendRight]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
PG only
Whether the range extends to the right of the other range.
@example:
{ rangeAttribute: { [Op.noExtendRight]: [1, 2] } }// results in// "rangeAttribute" &< [1, 2)https://www.postgresql.org/docs/14/functions-range.html
property [Op.not]
[Op.not]?: WhereOperators<AttributeType>[typeof Op.eq];
@example:
[Op.not]: true
becomesIS NOT TRUE
@example:{ col: { [Op.not]: { [Op.gt]: 5 } } }
becomesNOT (col > 5)
property [Op.notBetween]
[Op.notBetween]?: WhereOperators<AttributeType>[typeof Op.between];
@example:
[Op.notBetween]: [11, 15],
becomesNOT BETWEEN 11 AND 15
property [Op.notILike]
[Op.notILike]?: WhereOperators<AttributeType>[typeof Op.like];
PG only
@example:
[Op.notILike]: '%hat'
becomesNOT ILIKE '%hat'
@example:[Op.notLike]: ['cat', 'hat']
becomesLIKE ANY ARRAY['cat', 'hat']
property [Op.notIn]
[Op.notIn]?: WhereOperators<AttributeType>[typeof Op.in];
@example:
[Op.notIn]: [1, 2],
becomesNOT IN (1, 2)
property [Op.notIRegexp]
[Op.notIRegexp]?: WhereOperators<AttributeType>[typeof Op.regexp];
PG only
Does not match regular expression, case insensitive
@example:
[Op.notIRegexp]: '^[h|a|t]'
becomes!~* '^[h|a|t]'
property [Op.notLike]
[Op.notLike]?: WhereOperators<AttributeType>[typeof Op.like];
@example:
[Op.notLike]: '%hat'
becomesNOT LIKE '%hat'
@example:[Op.notLike]: { [Op.any]: ['cat', 'hat']}
becomesNOT LIKE ANY ARRAY['cat', 'hat']
property [Op.notRegexp]
[Op.notRegexp]?: WhereOperators<AttributeType>[typeof Op.regexp];
MySQL/PG only
Does not match regular expression, case sensitive
@example:
[Op.notRegexp]: '^[h|a|t]'
becomesNOT REGEXP/!~ '^[h|a|t]'
property [Op.overlap]
[Op.overlap]?: AllowAnyAll< | // RANGE && RANGE (AttributeType extends Range<infer RangeType> ? Rangable<RangeType> : // ARRAY && ARRAY AttributeType extends any[] ? StaticValues<NonNullable<AttributeType>> : never) | DynamicValues<AttributeType>>;
PG array & range 'overlaps' operator
@example:
[Op.overlap]: [1, 2]
becomes&& [1, 2]
property [Op.regexp]
[Op.regexp]?: AllowAnyAll<OperatorValues<Extract<AttributeType, string>>>;
MySQL/PG only
Matches regular expression, case sensitive
@example:
[Op.regexp]: '^[h|a|t]'
becomesREGEXP/~ '^[h|a|t]'
property [Op.startsWith]
[Op.startsWith]?: OperatorValues<Extract<AttributeType, string>>;
Strings starts with value.
property [Op.strictLeft]
[Op.strictLeft]?: AttributeType extends Range<infer RangeType> ? Rangable<RangeType> : never | DynamicValues<AttributeType>;
PG only
Whether the range is strictly left of the other range.
@example:
{ rangeAttribute: { [Op.strictLeft]: [1, 2] } }// results in// "rangeAttribute" << [1, 2)https://www.postgresql.org/docs/14/functions-range.html
property [Op.strictRight]
[Op.strictRight]?: WhereOperators<AttributeType>[typeof Op.strictLeft];
PG only
Whether the range is strictly right of the other range.
@example:
{ rangeAttribute: { [Op.strictRight]: [1, 2] } }// results in// "rangeAttribute" >> [1, 2)https://www.postgresql.org/docs/14/functions-range.html
property [Op.substring]
[Op.substring]?: WhereOperators<AttributeType>[typeof Op.startsWith];
String contains value.
Enums
enum LOCK
enum LOCK { UPDATE = 'UPDATE', SHARE = 'SHARE', KEY_SHARE = 'KEY SHARE', NO_KEY_UPDATE = 'NO KEY UPDATE',}
Possible options for row locking. Used in conjunction with
find
calls:t1 // is a transactiont1.LOCK.UPDATE,t1.LOCK.SHARE,t1.LOCK.KEY_SHARE, // Postgres 9.3+ onlyt1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ onlyUsage:
t1 // is a transactionModel.findAll({where: ...,transaction: t1,lock: t1.LOCK...});Postgres also supports specific locks while eager loading by using OF:
UserModel.findAll({where: ...,include: [TaskModel, ...],transaction: t1,lock: {level: t1.LOCK...,of: UserModel}});UserModel will be locked but TaskModel won't!
member KEY_SHARE
KEY_SHARE = 'KEY SHARE'
Postgres 9.3+ only
member NO_KEY_UPDATE
NO_KEY_UPDATE = 'NO KEY UPDATE'
Postgres 9.3+ only
member SHARE
SHARE = 'SHARE'
member UPDATE
UPDATE = 'UPDATE'
enum ValidationErrorItemOrigin
enum ValidationErrorItemOrigin { CORE = 'CORE', DB = 'DB', FUNCTION = 'FUNCTION',}
An enum that defines valid ValidationErrorItem
origin
values
member CORE
CORE = 'CORE'
specifies errors that originate from the sequelize "core"
member DB
DB = 'DB'
specifies validation errors that originate from the storage engine
member FUNCTION
FUNCTION = 'FUNCTION'
specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
enum ValidationErrorItemType
enum ValidationErrorItemType { 'notnull violation' = 'CORE', 'string violation' = 'CORE', 'unique violation' = 'DB', 'validation error' = 'FUNCTION',}
An enum that is used internally by the
ValidationErrorItem
class that maps currenttype
strings (as given to ValidationErrorItem.constructor()) to our neworigin
values.
member 'notnull violation'
'notnull violation' = 'CORE'
member 'string violation'
'string violation' = 'CORE'
member 'unique violation'
'unique violation' = 'DB'
member 'validation error'
'validation error' = 'FUNCTION'
Type Aliases
type AddConstraintOptions
type AddConstraintOptions = | AddUniqueConstraintOptions | AddDefaultConstraintOptions | AddCheckConstraintOptions | AddPrimaryKeyConstraintOptions | AddForeignKeyConstraintOptions;
type AllowReadonlyArray
type AllowReadonlyArray<T> = T | readonly T[];
type Attributes
type Attributes<M extends Model | Hooks> = M['_attributes'];
Returns the creation attributes of a given Model.
This returns the Attributes of a Model that have already been defined, it does not build them. If you need to build them, use InferAttributes.
Example 1
function getValue<M extends Model>(modelClass: ModelStatic, attribute: keyof Attributes) {}
type AttributeType
type AttributeType = WhereLeftOperand;
Deprecated
use WhereLeftOperand instead.
type BelongsToCreateAssociationMixin
type BelongsToCreateAssociationMixin<TModel extends Model> = ( values?: CreationAttributes<TModel>, options?: BelongsToCreateAssociationMixinOptions) => Promise<TModel>;
The createAssociation mixin applied to models with belongsTo. An example of usage is as follows:
User.belongsTo(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRole...// setRole...createRole: Sequelize.BelongsToCreateAssociationMixin<RoleAttributes>;}See Also
https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html
Instance
type BelongsToGetAssociationMixin
type BelongsToGetAssociationMixin<TModel> = ( options?: BelongsToGetAssociationMixinOptions) => Promise<TModel>;
The getAssociation mixin applied to models with belongsTo. An example of usage is as follows:
User.belongsTo(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttrib>, UserAttrib {getRole: Sequelize.BelongsToGetAssociationMixin<RoleInstance>;// setRole...// createRole...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html
Instance
type BelongsToManyAddAssociationMixin
type BelongsToManyAddAssociationMixin<TModel, TModelPrimaryKey> = ( newAssociation?: TModel | TModelPrimaryKey, options?: BelongsToManyAddAssociationMixinOptions) => Promise<void>;
The addAssociation mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...addRole: Sequelize.BelongsToManyAddAssociationMixin<RoleInstance, RoleId, UserRoleAttributes>;// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyAddAssociationsMixin
type BelongsToManyAddAssociationsMixin<TModel, TModelPrimaryKey> = ( newAssociations?: (TModel | TModelPrimaryKey)[], options?: BelongsToManyAddAssociationsMixinOptions) => Promise<void>;
The addAssociations mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...addRoles: Sequelize.BelongsToManyAddAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyCountAssociationsMixin
type BelongsToManyCountAssociationsMixin = ( options?: BelongsToManyCountAssociationsMixinOptions) => Promise<number>;
The countAssociations mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...countRoles: Sequelize.BelongsToManyCountAssociationsMixin;}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyCreateAssociationMixin
type BelongsToManyCreateAssociationMixin<TModel extends Model> = ( values?: CreationAttributes<TModel>, options?: BelongsToManyCreateAssociationMixinOptions) => Promise<TModel>;
The createAssociation mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...createRole: Sequelize.BelongsToManyCreateAssociationMixin<RoleAttributes, UserRoleAttributes>;// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyGetAssociationsMixin
type BelongsToManyGetAssociationsMixin<TModel> = ( options?: BelongsToManyGetAssociationsMixinOptions) => Promise<TModel[]>;
The getAssociations mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {getRoles: Sequelize.BelongsToManyGetAssociationsMixin<RoleInstance>;// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyHasAssociationMixin
type BelongsToManyHasAssociationMixin<TModel, TModelPrimaryKey> = ( target: TModel | TModelPrimaryKey, options?: BelongsToManyHasAssociationMixinOptions) => Promise<boolean>;
The hasAssociation mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles...hasRole: Sequelize.BelongsToManyHasAssociationMixin<RoleInstance, RoleId>;// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyHasAssociationsMixin
type BelongsToManyHasAssociationsMixin<TModel, TModelPrimaryKey> = ( targets: (TModel | TModelPrimaryKey)[], options?: BelongsToManyHasAssociationsMixinOptions) => Promise<boolean>;
The removeAssociations mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles// hasRole...hasRoles: Sequelize.BelongsToManyHasAssociationsMixin<RoleInstance, RoleId>;// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyRemoveAssociationMixin
type BelongsToManyRemoveAssociationMixin<TModel, TModelPrimaryKey> = ( oldAssociated?: TModel | TModelPrimaryKey, options?: BelongsToManyRemoveAssociationMixinOptions) => Promise<void>;
The removeAssociation mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...removeRole: Sequelize.BelongsToManyRemoveAssociationMixin<RoleInstance, RoleId>;// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManyRemoveAssociationsMixin
type BelongsToManyRemoveAssociationsMixin<TModel, TModelPrimaryKey> = ( oldAssociateds?: (TModel | TModelPrimaryKey)[], options?: BelongsToManyRemoveAssociationsMixinOptions) => Promise<void>;
The removeAssociations mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...removeRoles: Sequelize.BelongsToManyRemoveAssociationsMixin<RoleInstance, RoleId>;// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToManySetAssociationsMixin
type BelongsToManySetAssociationsMixin<TModel, TModelPrimaryKey> = ( newAssociations?: (TModel | TModelPrimaryKey)[], options?: BelongsToManySetAssociationsMixinOptions) => Promise<void>;
The setAssociations mixin applied to models with belongsToMany. An example of usage is as follows:
User.belongsToMany(Role, { through: UserRole });interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...setRoles: Sequelize.BelongsToManySetAssociationsMixin<RoleInstance, RoleId, UserRoleAttributes>;// addRoles...// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
Instance
type BelongsToSetAssociationMixin
type BelongsToSetAssociationMixin<TModel, TPrimaryKey> = ( newAssociation?: TModel | TPrimaryKey, options?: BelongsToSetAssociationMixinOptions) => Promise<void>;
The setAssociation mixin applied to models with belongsTo. An example of usage is as follows:
User.belongsTo(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRole...setRole: Sequelize.BelongsToSetAssociationMixin<RoleInstance, RoleId>;// createRole...}See Also
https://sequelize.org/master/class/lib/associations/belongs-to.js~BelongsTo.html
Instance
type BindOrReplacements
type BindOrReplacements = { [key: string]: unknown } | unknown[];
type BlobSize
type BlobSize = 'tiny' | 'medium' | 'long';
type ColumnReference
type ColumnReference = Col | { [Op.col]: string };
Internal type - prone to changes. Do not export.
type CountWithOptions
type CountWithOptions<TAttributes = any> = SetRequired< CountOptions<TAttributes>, 'group'>;
Options for Model.count when GROUP BY is used
type CreationAttributes
type CreationAttributes<M extends Model | Hooks> = MakeNullishOptional< M['_creationAttributes']>;
Returns the creation attributes of a given Model.
This returns the Creation Attributes of a Model, it does not build them. If you need to build them, use InferCreationAttributes.
Example 1
function buildModel<M extends Model>(modelClass: ModelStatic, attributes: CreationAttributes) {}
type CreationOptional
type CreationOptional<T> = // we don't brand null & undefined as they can't have properties. // This means `CreationOptional<null>` will not work, but who makes an attribute that only accepts null? // Note that `CreationOptional<string | null>` does work! T extends null | undefined ? T : T & { [CreationAttributeBrand]?: true };
This is a Branded Type. You can use it to tag attributes that can be ommited during Model Creation.
For use with InferCreationAttributes.
type DataType
type DataType = string | AbstractDataTypeConstructor | AbstractDataType;
type DataTypeAbstract
type DataTypeAbstract = AbstractDataTypeConstructor;
type Dialect
type Dialect = | 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle';
type FieldMap
type FieldMap = { [key: string]: string };
type FindAttributeOptions
type FindAttributeOptions = | (string | ProjectionAlias)[] | { exclude: string[]; include?: (string | ProjectionAlias)[]; } | { exclude?: string[]; include: (string | ProjectionAlias)[]; };
type ForeignKey
type ForeignKey<T> = // we don't brand null & undefined as they can't have properties. // This means `ForeignKey<null>` will not work, but who makes an attribute that only accepts null? // Note that `ForeignKey<string | null>` does work! T extends null | undefined ? T : T & { [ForeignKeyBrand]?: true };
This is a Branded Type. You can use it to tag fields from your class that are foreign keys. They will become optional in Model.init (as foreign keys are added by association methods, like Model.hasMany.
type GroupOption
type GroupOption = string | Fn | Col | (string | Fn | Col)[];
type HasManyAddAssociationMixin
type HasManyAddAssociationMixin<TModel, TModelPrimaryKey> = ( newAssociation?: TModel | TModelPrimaryKey, options?: HasManyAddAssociationMixinOptions) => Promise<void>;
The addAssociation mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...addRole: Sequelize.HasManyAddAssociationMixin<RoleInstance, RoleId>;// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyAddAssociationsMixin
type HasManyAddAssociationsMixin<TModel, TModelPrimaryKey> = ( newAssociations?: (TModel | TModelPrimaryKey)[], options?: HasManyAddAssociationsMixinOptions) => Promise<void>;
The addAssociations mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...addRoles: Sequelize.HasManyAddAssociationsMixin<RoleInstance, RoleId>;// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyCountAssociationsMixin
type HasManyCountAssociationsMixin = ( options?: HasManyCountAssociationsMixinOptions) => Promise<number>;
The countAssociations mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...countRoles: Sequelize.HasManyCountAssociationsMixin;}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyCreateAssociationMixin
type HasManyCreateAssociationMixin< TModel extends Model, TForeignKey extends keyof CreationAttributes<TModel> = never, TScope extends keyof CreationAttributes<TModel> = never> = ( values?: Omit<CreationAttributes<TModel>, TForeignKey | TScope>, options?: HasManyCreateAssociationMixinOptions) => Promise<TModel>;
The createAssociation mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...createRole: Sequelize.HasManyCreateAssociationMixin<RoleAttributes>;// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyGetAssociationsMixin
type HasManyGetAssociationsMixin<TModel> = ( options?: HasManyGetAssociationsMixinOptions) => Promise<TModel[]>;
The getAssociations mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {getRoles: Sequelize.HasManyGetAssociationsMixin<RoleInstance>;// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyHasAssociationMixin
type HasManyHasAssociationMixin<TModel, TModelPrimaryKey> = ( target: TModel | TModelPrimaryKey, options?: HasManyHasAssociationMixinOptions) => Promise<boolean>;
The hasAssociation mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles...hasRole: Sequelize.HasManyHasAssociationMixin<RoleInstance, RoleId>;// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyHasAssociationsMixin
type HasManyHasAssociationsMixin<TModel, TModelPrimaryKey> = ( targets: (TModel | TModelPrimaryKey)[], options?: HasManyHasAssociationsMixinOptions) => Promise<boolean>;
The removeAssociations mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...// removeRoles// hasRole...hasRoles: Sequelize.HasManyHasAssociationsMixin<RoleInstance, RoleId>;// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyRemoveAssociationMixin
type HasManyRemoveAssociationMixin<TModel, TModelPrimaryKey> = ( oldAssociated?: TModel | TModelPrimaryKey, options?: HasManyRemoveAssociationMixinOptions) => Promise<void>;
The removeAssociation mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...removeRole: Sequelize.HasManyRemoveAssociationMixin<RoleInstance, RoleId>;// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManyRemoveAssociationsMixin
type HasManyRemoveAssociationsMixin<TModel, TModelPrimaryKey> = ( oldAssociateds?: (TModel | TModelPrimaryKey)[], options?: HasManyRemoveAssociationsMixinOptions) => Promise<void>;
The removeAssociations mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...// setRoles...// addRoles...// addRole...// createRole...// removeRole...removeRoles: Sequelize.HasManyRemoveAssociationsMixin<RoleInstance, RoleId>;// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasManySetAssociationsMixin
type HasManySetAssociationsMixin<TModel, TModelPrimaryKey> = ( newAssociations?: (TModel | TModelPrimaryKey)[], options?: HasManySetAssociationsMixinOptions) => Promise<void>;
The setAssociations mixin applied to models with hasMany. An example of usage is as follows:
User.hasMany(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRoles...setRoles: Sequelize.HasManySetAssociationsMixin<RoleInstance, RoleId>;// addRoles...// addRole...// createRole...// removeRole...// removeRoles...// hasRole...// hasRoles...// countRoles...}See Also
https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
Instance
type HasOneCreateAssociationMixin
type HasOneCreateAssociationMixin<TModel extends Model> = ( values?: CreationAttributes<TModel>, options?: HasOneCreateAssociationMixinOptions) => Promise<TModel>;
The createAssociation mixin applied to models with hasOne. An example of usage is as follows:
User.hasOne(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRole...// setRole...createRole: Sequelize.HasOneCreateAssociationMixin<RoleAttributes>;}See Also
https://sequelize.org/master/class/lib/associations/has-one.js~HasOne.html
Instance
type HasOneGetAssociationMixin
type HasOneGetAssociationMixin<TModel> = ( options?: HasOneGetAssociationMixinOptions) => Promise<TModel>;
The getAssociation mixin applied to models with hasOne. An example of usage is as follows:
User.hasOne(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttrib>, UserAttrib {getRole: Sequelize.HasOneGetAssociationMixin<RoleInstance>;// setRole...// createRole...}See Also
https://sequelize.org/master/class/lib/associations/has-one.js~HasOne.html
Instance
type HasOneSetAssociationMixin
type HasOneSetAssociationMixin<TModel, TModelPrimaryKey> = ( newAssociation?: TModel | TModelPrimaryKey, options?: HasOneSetAssociationMixinOptions) => Promise<void>;
The setAssociation mixin applied to models with hasOne. An example of usage is as follows:
User.hasOne(Role);interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {// getRole...setRole: Sequelize.HasOneSetAssociationMixin<RoleInstance, RoleId>;// createRole...}See Also
https://sequelize.org/master/class/lib/associations/has-one.js~HasOne.html
Instance
type Identifier
type Identifier = number | bigint | string | Buffer;
Possible types for primary keys
type Includeable
type Includeable = | ModelType | Association | IncludeOptions | { all: true; nested?: true } | string;
Options for eager-loading associated models, also allowing for all associations to be loaded at once
type IndexMethod
type IndexMethod = 'BTREE' | 'HASH' | 'GIST' | 'SPGIST' | 'GIN' | 'BRIN' | string;
type IndexType
type IndexType = 'UNIQUE' | 'FULLTEXT' | 'SPATIAL';
type InferAttributes
type InferAttributes< M extends Model, Options extends InferAttributesOptions<keyof M | never | ''> = { omit: never }> = { [Key in keyof M as InternalInferAttributeKeysFromFields< M, Key, Options >]: M[Key];};
Utility type to extract Attributes of a given Model class.
It returns all instance properties defined in the Model, except: - those inherited from Model (intermediate inheritance works), - the ones whose type is a function, - the ones manually excluded using the second parameter. - the ones branded using NonAttribute
It cannot detect whether something is a getter or not, you should use the
Excluded
parameter to exclude getter & setters from the attribute list.Example 1
// listed attributes will be 'id' & 'firstName'. class User extends Model<InferAttributes> { id: number; firstName: string; }
Example 2
// listed attributes will be 'id' & 'firstName'. // we're excluding the
name
getter &projects
attribute using theomit
option. class User extends Model<InferAttributes<User, { omit: 'name' | 'projects' }>> { id: number; firstName: string;// this is a getter, not an attribute. It should not be listed in attributes. get name(): string { return this.firstName; } // this is an association, it should not be listed in attributes projects?: Project[]; }
Example 3
// listed attributes will be 'id' & 'firstName'. // we're excluding the
name
getter &test
attribute using theNonAttribute
branded type. class User extends Model<InferAttributes> { id: number; firstName: string;// this is a getter, not an attribute. It should not be listed in attributes. get name(): NonAttribute { return this.firstName; } // this is an association, it should not be listed in attributes projects?: NonAttribute<Project[]>; }
type InferCreationAttributes
type InferCreationAttributes< M extends Model, Options extends InferAttributesOptions<keyof M | never | ''> = { omit: never }> = { [Key in keyof M as InternalInferAttributeKeysFromFields< M, Key, Options >]: IsBranded<M[Key], typeof CreationAttributeBrand> extends true ? M[Key] | undefined : M[Key];};
Utility type to extract Creation Attributes of a given Model class.
Works like InferAttributes, but fields that are tagged using CreationOptional will be optional.
Example 1
class User extends Model<InferAttributes, InferCreationAttributes> { // this attribute is optional in Model#create declare id: CreationOptional;
// this attribute is mandatory in Model#create declare name: string; }
type LogicType
type LogicType = | Fn | Col | Literal | OrOperator<any> | AndOperator<any> | WhereOperators | string | symbol | null;
Deprecated
this is not used anymore, typing definitions for where have changed to more accurately reflect reality.
type ModelAttributes
type ModelAttributes<M extends Model = Model, TAttributes = any> = { /** * The description of a database column */ [name in keyof TAttributes]: DataType | ModelAttributeColumnOptions<M>;};
Interface for Attributes provided for all columns in a model
type ModelCtor
type ModelCtor<M extends Model> = ModelStatic<M>;
Deprecated
use ModelStatic
type ModelDefined
type ModelDefined<S extends {}, T extends {}> = ModelStatic<Model<S, T>>;
type ModelIndexesOptions
type ModelIndexesOptions = IndexesOptions;
Interface for indexes property in InitOptions
type ModelStatic
type ModelStatic<M extends Model> = NonConstructor<typeof Model> & { new (): M };
type ModelType
type ModelType< TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes> = new () => Model<TModelAttributes, TCreationAttributes>;
Deprecated
use ModelStatic
type NonAttribute
type NonAttribute<T> = // we don't brand null & undefined as they can't have properties. // This means `NonAttribute<null>` will not work, but who makes an attribute that only accepts null? // Note that `NonAttribute<string | null>` does work! T extends null | undefined ? T : T & { [NonAttributeBrand]?: true };
This is a Branded Type. You can use it to tag fields from your class that are NOT attributes. They will be ignored by InferAttributes and InferCreationAttributes
type Optional
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
Type helper for making certain fields of an object optional. This is helpful for creating the
CreationAttributes
from yourAttributes
for a Model.
type Order
type Order = Fn | Col | Literal | OrderItem[];
type OrderItem
type OrderItem = | string | Fn | Col | Literal | [OrderItemColumn, string] | [OrderItemAssociation, OrderItemColumn] | [OrderItemAssociation, OrderItemColumn, string] | [OrderItemAssociation, OrderItemAssociation, OrderItemColumn] | [OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string] | [ OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn ] | [ OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string ] | [ OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn ] | [ OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string ];
type ProjectionAlias
type ProjectionAlias = readonly [string | Literal | Fn | Col, string];
Please note if this is used the aliased property will not be available on the model instance as a property but only via
instance.get('alias')
.
type Rangable
type Rangable<T> = | readonly [ lower: T | RangePart<T | number> | number | null, higher: T | RangePart<T | number> | number | null ] | EmptyRange;
type Range
type Range<T> = | readonly [lower: RangePart<T | number>, higher: RangePart<T | number>] | EmptyRange;
This type represents the output of the RANGE data type.
type RangeableDataType
type RangeableDataType = | IntegerDataTypeConstructor | IntegerDataType | BigIntDataTypeConstructor | BigIntDataType | DecimalDataTypeConstructor | DecimalDataType | DateOnlyDataTypeConstructor | DateOnlyDataType | DateDataTypeConstructor | DateDataType;
type RetryOptions
type RetryOptions = RetryAsPromisedOptions;
type TableName
type TableName = string | TableNameWithSchema;
type TextLength
type TextLength = 'tiny' | 'medium' | 'long';
type WhereAttributeHash
type WhereAttributeHash<TAttributes = any> = { // support 'attribute' & '$attribute$' [AttributeName in keyof TAttributes as AttributeName extends string ? AttributeName | `$${AttributeName}$` : never]?: WhereAttributeHashValue<TAttributes[AttributeName]>;} & { [AttributeName in keyof TAttributes as AttributeName extends string ? // support 'json.path', '$json$.path' | `${AttributeName}.${string}` | `$${AttributeName}$.${string}` // support 'attribute::cast', '$attribute$::cast', 'json.path::cast' & '$json$.path::cast' | `${ | AttributeName | `$${AttributeName}$` | `${AttributeName}.${string}` | `$${AttributeName}$.${string}`}::${string}` : never]?: WhereAttributeHashValue<any>;} & { // support '$nested.attribute$', '$nested.attribute$::cast', '$nested.attribute$.json.path', & '$nested.attribute$.json.path::cast' // TODO [2022-05-26]: Remove this ts-ignore once we drop support for TS < 4.4 // TypeScript < 4.4 does not support using a Template Literal Type as a key. // note: this *must* be a ts-ignore, as it works in ts >= 4.4 // @ts-ignore [ attribute: | `$${string}.${string}$` | `$${string}.${string}$::${string}` | `$${string}.${string}$.${string}` | `$${string}.${string}$.${string}::${string}` ]: WhereAttributeHashValue<any>;};
A hash of attributes to describe your search.
Possible key values:
- An attribute name:
{ id: 1 }
- A nested attribute:{ '$projects.id$': 1 }
- A JSON key:{ 'object.key': 1 }
- A cast:{ 'id::integer': 1 }
- A combination of the above:
{ '$join.attribute$.json.path::integer': 1 }
type WhereAttributeHashValue
type WhereAttributeHashValue<AttributeType> = | AllowNotOrAndRecursive< // if the right-hand side is an array, it will be equal to Op.in // otherwise it will be equal to Op.eq // Exception: array attribtues always use Op.eq, never Op.in. AttributeType extends any[] ? | WhereOperators<AttributeType>[typeof Op.eq] | WhereOperators<AttributeType> : | WhereOperators<AttributeType>[typeof Op.in] | WhereOperators<AttributeType>[typeof Op.eq] | WhereOperators<AttributeType> > // TODO: this needs a simplified version just for JSON columns | WhereAttributeHash<any>;
Types that can be compared to an attribute in a WHERE context.
type WhereLeftOperand
type WhereLeftOperand = | Fn | ColumnReference | Literal | Cast | ModelAttributeColumnOptions;
type WhereOptions
type WhereOptions<TAttributes = any> = AllowNotOrAndWithImplicitAndArrayRecursive< WhereAttributeHash<TAttributes> | Literal | Fn | Where | Json>;
The type accepted by every
where
option
type WhereValue
type WhereValue<TAttributes = any> = | string | number | bigint | boolean | Date | Buffer | null | WhereAttributeHash<any> // for JSON columns | Col // reference another column | Fn | WhereGeometryOptions;
Used for the right hand side of WhereAttributeHash. WhereAttributeHash is in there for JSON columns.
Deprecated
do not use me
Namespaces
namespace Transaction
namespace Transaction {}
enum ISOLATION_LEVELS
enum ISOLATION_LEVELS { READ_UNCOMMITTED = 'READ UNCOMMITTED', READ_COMMITTED = 'READ COMMITTED', REPEATABLE_READ = 'REPEATABLE READ', SERIALIZABLE = 'SERIALIZABLE',}
Isolations levels can be set per-transaction by passing
options.isolationLevel
tosequelize.transaction
. Default toREPEATABLE_READ
but you can override the default isolation level by passingoptions.isolationLevel
innew Sequelize
.The possible isolations levels to use when starting a transaction:
{READ_UNCOMMITTED: "READ UNCOMMITTED",READ_COMMITTED: "READ COMMITTED",REPEATABLE_READ: "REPEATABLE READ",SERIALIZABLE: "SERIALIZABLE"}Pass in the desired level as the first argument:
try {await sequelize.transaction({isolationLevel: Sequelize.Transaction.SERIALIZABLE}, transaction => {// your transactions});// transaction has been committed. Do something after the commit if required.} catch(err) {// do something with the err.}
member READ_COMMITTED
READ_COMMITTED = 'READ COMMITTED'
member READ_UNCOMMITTED
READ_UNCOMMITTED = 'READ UNCOMMITTED'
member REPEATABLE_READ
REPEATABLE_READ = 'REPEATABLE READ'
member SERIALIZABLE
SERIALIZABLE = 'SERIALIZABLE'
Package Files (40)
- types/associations/base.d.ts
- types/associations/belongs-to-many.d.ts
- types/associations/belongs-to.d.ts
- types/associations/has-many.d.ts
- types/associations/has-one.d.ts
- types/data-types.d.ts
- types/dialects/abstract/query-interface.d.ts
- types/dialects/mssql/async-queue.d.ts
- types/errors/aggregate-error.d.ts
- types/errors/association-error.d.ts
- types/errors/base-error.d.ts
- types/errors/bulk-record-error.d.ts
- types/errors/connection-error.d.ts
- types/errors/connection/access-denied-error.d.ts
- types/errors/connection/connection-acquire-timeout-error.d.ts
- types/errors/connection/connection-refused-error.d.ts
- types/errors/connection/connection-timed-out-error.d.ts
- types/errors/connection/host-not-found-error.d.ts
- types/errors/connection/host-not-reachable-error.d.ts
- types/errors/connection/invalid-connection-error.d.ts
- types/errors/database-error.d.ts
- types/errors/database/exclusion-constraint-error.d.ts
- types/errors/database/foreign-key-constraint-error.d.ts
- types/errors/database/timeout-error.d.ts
- types/errors/database/unknown-constraint-error.d.ts
- types/errors/eager-loading-error.d.ts
- types/errors/empty-result-error.d.ts
- types/errors/instance-error.d.ts
- types/errors/optimistic-lock-error.d.ts
- types/errors/query-error.d.ts
- types/errors/sequelize-scope-error.d.ts
- types/errors/validation-error.d.ts
- types/errors/validation/unique-constraint-error.d.ts
- types/index.d.ts
- types/model.d.ts
- types/operators.d.ts
- types/sequelize.d.ts
- types/transaction.d.ts
- types/utils.d.ts
- types/utils/validator-extras.d.ts
Dependencies (16)
Dev Dependencies (60)
- @commitlint/cli
- @commitlint/config-angular
- @octokit/rest
- @octokit/types
- @types/chai
- @types/lodash
- @types/mocha
- @types/node
- @types/sinon
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- acorn
- chai
- chai-as-promised
- chai-datetime
- cheerio
- cls-hooked
- copyfiles
- cross-env
- delay
- esbuild
- esdoc
- esdoc-ecmascript-proposal-plugin
- esdoc-inject-style-plugin
- esdoc-standard-plugin
- eslint
- eslint-plugin-jsdoc
- eslint-plugin-mocha
- expect-type
- fast-glob
- fs-jetpack
- husky
- ibm_db
- js-combinatorics
- lcov-result-merger
- lint-staged
- mariadb
- markdownlint-cli
- mocha
- module-alias
- mysql2
- node-hook
- nyc
- oracledb
- p-map
- p-props
- p-settle
- p-timeout
- pg
- pg-hstore
- rimraf
- semantic-release
- semantic-release-fail-on-major-bump
- sinon
- sinon-chai
- snowflake-sdk
- source-map-support
- sqlite3
- tedious
- typescript
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/sequelize
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/sequelize)
- HTML<a href="https://www.jsdocs.io/package/sequelize"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 15560 ms. - Missing or incorrect documentation? Open an issue for this package.