Model
A Model represents a table in the database. Instances of this class represent a database row.
Model instances operate with the concept of a dataValues
property, which stores the actual values represented by the instance.
By default, the values from dataValues can also be accessed directly from the Instance, that is:
instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')
However, if getters and/or setters are defined for field
they will be invoked, instead of returning the value from dataValues
.
Accessing properties directly or using get
is preferred for regular use, getDataValue
should only be used for custom getters.
See:
- Sequelize#define for more information about getters and setters
Static Method Summary
Static Public Methods | ||
public static |
Add a new scope to the model. |
|
public static |
async aggregate(attribute: string, aggregateFunction: string, options: object): Promise<DataTypes|object> Run an aggregation method on the specified field |
|
public static |
Creates an association between this (the source) and the provided target. |
|
public static |
belongsToMany(target: Model, options: object): BelongsToMany Create an N:M association with a join table. |
|
public static |
Builds a new model instance. |
|
public static |
Create and insert multiple instances in bulk. |
|
public static |
Count the number of records matching the provided where clause. |
|
public static |
Builds a new model instance and calls save on it. |
|
public static |
Decrement the value of one or more columns. |
since 4.36.0 |
public static |
Run a describe query on the table. |
|
public static |
Delete multiple instances, or set their deletedAt timestamp to the current time if |
|
public static |
Drop the table represented by this Model |
|
public static |
Search for multiple instances. |
|
public static |
async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}> Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. |
|
public static |
Search for a single instance by its primary key._ |
|
public static |
async findCreateFind(options: object): Promise<Model, boolean> A more performant findOrCreate that may not work under a transaction (working in postgres) Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again |
|
public static |
Search for a single instance. |
|
public static |
async findOrBuild(options: object): Promise<Model, boolean> Find a row that matches the query, or build (but don't save) the row if none is found. The successful result of the promise will be (instance, built) |
|
public static |
async findOrCreate(options: object): Promise<Model, boolean> Find a row that matches the query, or build and save the row if none is found The successful result of the promise will be (instance, created) |
|
public static |
getAttributes(): object | any Returns the attributes of the model. |
|
public static |
getTableName(): string | object Get the table name of the model, taking schema into account. |
|
public static |
Creates a 1:m association between this (the source) and the provided target. |
|
public static |
Creates an association between this (the source) and the provided target. |
|
public static |
Increment the value of one or more columns. |
|
public static |
Initialize a model, representing a table in the DB, with attributes and options. |
|
public static |
Find the maximum value of field |
|
public static |
Find the minimum value of field |
|
public static |
removeAttribute(attribute: string) Remove attribute from model definition |
|
public static |
Restore multiple instances if |
|
public static |
Apply a schema to this model. |
|
public static |
Apply a scope created in |
|
public static |
Find the sum of field |
|
public static |
Sync this Model to the DB, that is create the table. |
|
public static |
Truncate all instances of the model. |
|
public static |
Get un-scoped model |
|
public static |
Update multiple instances that match the where options. |
|
public static |
Insert or update a single row. |
Constructor Summary
Public Constructor | ||
public |
constructor(values: object, options: object) Builds a new model instance. |
Member Summary
Public Members | ||
public |
isNewRecord: boolean: * Returns true if this instance has not yet been persisted to the database |
|
public get |
A reference to the sequelize instance |
Method Summary
Public Methods | ||
public |
If changed is called with a string it will return a boolean indicating whether the value of that key in |
|
public |
Decrement the value of one or more columns. |
|
public |
Destroy the row corresponding to this instance. |
|
public |
Check whether this and |
|
public |
equalsOneOf(others: Array<Model>): boolean Check if this is equal to one of |
|
public |
If no key is given, returns all values of the instance, also invoking virtual getters. |
|
public |
getDataValue(key: string): any Get the value of the underlying data value |
|
public |
Increment the value of one or more columns. |
since 4.0.0 |
public |
Helper method to determine if a instance is "soft deleted". |
|
public |
Returns the previous value for key from |
|
public |
Refresh the current instance in-place, i.e. |
|
public |
Restore the row corresponding to this instance. |
|
public |
Validates this instance, and if the validation passes, persists it to the database. |
|
public |
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 |
|
public |
setDataValue(key: string, value: any) Update the underlying data value |
|
public |
Convert the instance to a JSON representation. |
|
public |
This is the same as calling |
|
public |
Validate the attributes of this instance according to validation rules set in the model definition. |
|
public |
Get an object representing the query for this instance, use with |
Static Public Methods
public static addScope(name: string, scope: object | Function, options: object) source
Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined.
By default this will throw an error if a scope with that name already exists. Pass override: true
in the options object to silence this error.
public static async aggregate(attribute: string, aggregateFunction: string, options: object): Promise<DataTypes|object> source
Run an aggregation method on the specified field
Params:
Name | Type | Attribute | Description |
attribute | string | The attribute to aggregate over. Can be a field name or * |
|
aggregateFunction | string | The function to use for aggregation, e.g. sum, max etc. |
|
options | object |
|
Query options. See sequelize.query for full options |
options.where | object |
|
A hash of search attributes. |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.dataType | DataTypes | string |
|
The type of the result. If |
options.distinct | boolean |
|
Applies DISTINCT to the field being aggregated over |
options.transaction | Transaction |
|
Transaction to run query under |
options.plain | boolean |
|
When |
public static belongsTo(target: Model, options: object): BelongsTo source
Creates an association between this (the source) and the provided target. The foreign key is added on the source.
Params:
Name | Type | Attribute | Description |
target | Model | The target model |
|
options | object |
|
belongsTo association options |
options.hooks | boolean |
|
Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if |
options.as | string |
|
The alias of this model, in singular form. See also the |
options.foreignKey | string | object |
|
The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see |
options.targetKey | string |
|
The name of the attribute to use as the key for the association in the target table. Defaults to the primary key of the target table |
options.onDelete | string |
|
SET NULL if foreignKey allows nulls, NO ACTION if otherwise |
options.onUpdate | string |
|
Sets 'ON UPDATE' |
options.constraints | boolean |
|
Should on update and on delete constraints be enabled on the foreign key. |
Example:
Profile.belongsTo(User) // This will add userId to the profile table
public static belongsToMany(target: Model, options: object): BelongsToMany source
Create an N:M association with a join table. Defining through
is required.
Params:
Name | Type | Attribute | Description |
target | Model | Target model |
|
options | object | belongsToMany association options |
|
options.hooks | boolean |
|
Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if |
options.through | Model | string | object | The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it. |
|
options.through.model | Model |
|
The model used to join both sides of the N:M association. |
options.through.scope | object |
|
A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model) |
options.through.unique | boolean |
|
If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes) |
options.through.paranoid | boolean |
|
If true the generated join table will be paranoid |
options.as | string | object |
|
The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with |
options.foreignKey | string | object |
|
The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see |
options.otherKey | string | object |
|
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 |
options.scope | object |
|
A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) |
options.timestamps | boolean |
|
Should the join model have timestamps |
options.onDelete | string |
|
Cascade if this is a n:m, and set null if it is a 1:m |
options.onUpdate | string |
|
Sets |
options.constraints | boolean |
|
Should on update and on delete constraints be enabled on the foreign key. |
Example:
// Automagically generated join model
User.belongsToMany(Project, { through: 'UserProjects' })
Project.belongsToMany(User, { through: 'UserProjects' })
// Join model with additional attributes
const UserProjects = sequelize.define('UserProjects', {
started: Sequelize.BOOLEAN
})
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
public static build(values: object | Array, options: object): Model | Array<Model> source
Builds a new model instance.
Params:
Name | Type | Attribute | Description |
values | object | Array | An object of key value pairs or an array of such. If an array, the function will return an array of instances. |
|
options | object |
|
Instance build options |
options.raw | boolean |
|
If set to true, values will ignore field and virtual setters. |
options.isNewRecord | boolean |
|
Is this new record |
options.include | Array |
|
an array of include options - Used to build prefetched/included model instances. See |
public static async bulkCreate(records: Array, options: object): Promise<Array<Model>> source
Create and insert multiple instances in bulk.
The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records. To obtain Instances for the newly created values, you will need to query for them again.
If validation fails, the promise is rejected with an array-like AggregateError
Params:
Name | Type | Attribute | Description |
records | Array | List of objects (key/value pairs) to create instances from |
|
options | object |
|
Bulk create options |
options.fields | Array |
|
Fields to insert (defaults to all fields) |
options.validate | boolean |
|
Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation |
options.hooks | boolean |
|
Run before / after bulk create hooks? |
options.individualHooks | boolean |
|
Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true. |
options.ignoreDuplicates | boolean |
|
Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5) |
options.updateOnDuplicate | Array |
|
Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5). |
options.conflictAttributes | Array |
|
Optional override for the conflict fields in the ON CONFLICT part of the query. Only supported in Postgres >= 9.5 and SQLite >= 3.24.0 |
options.transaction | Transaction |
|
Transaction to run query under |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.returning | boolean | Array |
|
If true, append RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only) |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
public static async count(options: object): Promise<number> source
Count the number of records matching the provided where clause.
If you provide an include
option, the number of matching associations will be counted instead.
Params:
Name | Type | Attribute | Description |
options | object |
|
options |
options.where | object |
|
A hash of search attributes. |
options.include | object |
|
Include options. See |
options.paranoid | boolean |
|
Set |
options.distinct | boolean |
|
Apply COUNT(DISTINCT(col)) on primary key or on options.col. |
options.col | string |
|
Column on which COUNT() should be applied |
options.attributes | Array |
|
Used in conjunction with |
options.group | Array |
|
For creating complex counts. Will return multiple rows as needed. |
options.transaction | Transaction |
|
Transaction to run query under |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
public static async create(values: object, options: object): Promise<Model> source
Builds a new model instance and calls save on it.
Params:
Name | Type | Attribute | Description |
values | object | Hash of data values to create new record with |
|
options | object |
|
Build and query options |
options.raw | boolean |
|
If set to true, values will ignore field and virtual setters. |
options.isNewRecord | boolean |
|
Is this new record |
options.include | Array |
|
An array of include options - Used to build prefetched/included model instances. See |
options.fields | string[] |
|
An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. |
options.silent | boolean |
|
If true, the updatedAt timestamp will not be updated. |
options.validate | boolean |
|
If false, validations won't be run. |
options.hooks | boolean |
|
Run before and after create / update + validate hooks |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.returning | boolean | Array |
|
Appends RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only) |
public static async decrement(fields: string | Array | object, options: object): Promise<Model[], ?number> since 4.36.0 source
Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
sql SET column = column - X WHERE foo = 'bar'
query. To get the correct value after a decrement into the Instance you should do a reload.
Params:
Name | Type | Attribute | Description |
fields | string | Array | object | If a string is provided, that column is incremented by the value of |
|
options | object | decrement options, similar to increment |
Return:
Promise<Model[], ?number> | returns an array of affected rows and affected count with |
Example:
Model.decrement('number', { where: { foo: 'bar' });
Model.decrement(['number', 'count'], { by: 2, where: { foo: 'bar' } });
// `by` is ignored, since each column has its own value
Model.decrement({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
public static async describe(schema: string, options: object): Promise source
Run a describe query on the table.
public static async destroy(options: object): Promise<number> source
Delete multiple instances, or set their deletedAt timestamp to the current time if paranoid
is enabled.
Params:
Name | Type | Attribute | Description |
options | object | destroy options |
|
options.where | object |
|
Filter the destroy |
options.hooks | boolean |
|
Run before / after bulk destroy hooks? |
options.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 |
options.limit | number |
|
How many rows to delete |
options.force | boolean |
|
Delete instead of setting deletedAt to current timestamp (only applicable if |
options.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 |
options.cascade | boolean |
|
Only used in conjunction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE. |
options.restartIdentity | boolean |
|
Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table. |
options.transaction | Transaction |
|
Transaction to run query under |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
public static async drop(options: object): Promise source
Drop the table represented by this Model
Params:
Name | Type | Attribute | Description |
options | object |
|
drop options |
options.cascade | boolean |
|
Also drop all objects depending on this table, such as views. Only works in postgres |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
public static async findAll(options: object): Promise<Array<Model>> source
Search for multiple instances.
Params:
Name | Type | Attribute | Description |
options | object |
|
A hash of options to describe the scope of the search |
options.where | object |
|
A hash of attributes to describe your search. See above for examples. |
options.attributes | Array<string> | object |
|
A list of the attributes that you want to select, or an object with |
options.attributes.include | Array<string> |
|
Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. |
options.attributes.exclude | Array<string> |
|
Select all the attributes of the model, except some few. Useful for security purposes e.g. |
options.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.include | Array<object|Model|string> |
|
A list of associations to eagerly load using a left join. Supported is either |
options.include[].model | Model |
|
The model you want to eagerly load |
options.include[].as | string |
|
The alias of the relation, in case the model you want to eagerly load is aliased. For |
options.include[].association | Association |
|
The association you want to eagerly load. (This can be used instead of providing a model/as pair) |
options.include[].where | object |
|
Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set |
options.include[].or | boolean |
|
Whether to bind the ON and WHERE clause together by OR instead of AND. |
options.include[].on | object |
|
Supply your own ON condition for the join. |
options.include[].attributes | Array<string> |
|
A list of attributes to select from the child model |
options.include[].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 |
options.include[].right | boolean |
|
If true, converts to a right join if dialect support it. Ignored if |
options.include[].separate | boolean |
|
If true, runs a separate query to fetch the associated instances, only supported for hasMany associations |
options.include[].limit | number |
|
Limit the joined rows, only supported with include.separate=true |
options.include[].through.as | string |
|
The alias for the join model, in case you want to give it a different name than the default one. |
options.include[].through.paranoid | boolean |
|
If true, only non-deleted records will be returned from the join table. If false, both deleted and non-deleted records will be returned. Only applies if through model is paranoid. |
options.include[].through.where | object |
|
Filter on the join model for belongsToMany relations |
options.include[].through.attributes | Array |
|
A list of attributes to select from the join model for belongsToMany relations |
options.include[].include | Array<object|Model|string> |
|
Load further nested related models |
options.include[].duplicating | boolean |
|
Mark the include as duplicating, will prevent a subquery from being used. |
options.order | Array | fn | col | literal |
|
Specifies an ordering. Using an array, you can provide several columns / functions to order by. Each element can be further wrapped in a two-element array. The first element is the column / function to order by, the second is the direction. For example: |
options.limit | number |
|
Limit for result |
options.offset | number |
|
Offset for result |
options.transaction | Transaction |
|
Transaction to run query under |
options.lock | string | object |
|
Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. |
options.skipLocked | boolean |
|
Skip locked rows. Only supported in Postgres. |
options.raw | boolean |
|
Return raw result. See sequelize.query for more information. |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.having | object |
|
Having options |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.rejectOnEmpty | boolean | Error |
|
Throws an error when no records found |
options.dotNotation | boolean |
|
Allows including tables having the same attribute/column names - which have a dot in them. |
options.nest | boolean |
|
If true, transforms objects with |
Example:
Model.findAll({
where: {
attr1: 42,
attr2: 'cake'
}
})
# WHERE attr1 = 42 AND attr2 = 'cake'
const {gt, lte, ne, in: opIn} = Sequelize.Op;
Model.findAll({
where: {
attr1: {
[gt]: 50
},
attr2: {
[lte]: 45
},
attr3: {
[opIn]: [1,2,3]
},
attr4: {
[ne]: 5
}
}
})
# WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
const {or, and, gt, lt} = Sequelize.Op;
Model.findAll({
where: {
name: 'a project',
[or]: [
{id: [1, 2, 3]},
{
[and]: [
{id: {[gt]: 10}},
{id: {[lt]: 100}}
]
}
]
}
});
# WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
See:
- Operators for possible operators __Alias__: _all_ The promise is resolved with an array of Model instances if the query succeeds._
- Sequelize#query
public static async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}> source
Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for paging
Params:
Name | Type | Attribute | Description |
options | object |
|
See findAll options |
Example:
const result = await Model.findAndCountAll({
where: ...,
limit: 12,
offset: 12
});
# In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query.
# When you add includes, only those which are required (either because they have a where clause, or because `required` is explicitly set to true on the include) will be added to the count part.
# Suppose you want to find all users who have a profile attached:
User.findAndCountAll({
include: [
{ model: Profile, required: true}
],
limit: 3
});
# Because the include for `Profile` has `required` set it will result in an inner join, and only the users who have a profile will be counted. If we remove `required` from the include, both users with and without profiles will be counted
See:
- Model.findAll for a specification of find and query options
- Model.count for a specification of count options
public static async findByPk(param: number | bigint | string | Buffer, options: object): Promise<Model> source
Search for a single instance by its primary key._
Params:
Name | Type | Attribute | Description |
param | number | bigint | string | Buffer | The value of the desired instance's primary key. |
|
options | object |
|
find options |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
See:
- Model.findAll for a full explanation of options, Note that options.where is not supported.
public static async findCreateFind(options: object): Promise<Model, boolean> source
A more performant findOrCreate that may not work under a transaction (working in postgres) Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
See:
- Model.findAll for a full specification of find and options
public static async findOne(options: object): Promise<Model|null> source
Search for a single instance. Returns the first instance found, or null if none can be found.
Params:
Name | Type | Attribute | Description |
options | object |
|
A hash of options to describe the scope of the search |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
See:
- Model.findAll for an explanation of options
public static async findOrBuild(options: object): Promise<Model, boolean> source
Find a row that matches the query, or build (but don't save) the row if none is found. The successful result of the promise will be (instance, built)
Params:
Name | Type | Attribute | Description |
options | object | find options |
|
options.where | object | A hash of search attributes. If |
|
options.defaults | object |
|
Default values to use if building a new instance |
options.transaction | object |
|
Transaction to run query under |
public static async findOrCreate(options: object): Promise<Model, boolean> source
Find a row that matches the query, or build and save the row if none is found The successful result of the promise will be (instance, created)
If no transaction is passed in the options
object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call.
However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of sequelize. TimeoutError will be thrown instead.
If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
Params:
Name | Type | Attribute | Description |
options | object | find and create options |
|
options.where | object | where A hash of search attributes. If |
|
options.defaults | object |
|
Default values to use if creating a new instance |
options.transaction | Transaction |
|
Transaction to run query under |
See:
- Model.findAll for a full specification of find and options
public static getTableName(): string | object source
Get the table name of the model, taking schema into account. The method will return The name as a string if the model has no schema,
or an object with tableName
, schema
and delimiter
properties.
public static hasMany(target: Model, options: object): HasMany source
Creates a 1:m association between this (the source) and the provided target. The foreign key is added on the target.
Params:
Name | Type | Attribute | Description |
target | Model | Target model |
|
options | object |
|
hasMany association options |
options.hooks | boolean |
|
Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if |
options.as | string | object |
|
The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with |
options.foreignKey | string | object |
|
The name of the foreign key in the target table or an object representing the type definition for the foreign column (see |
options.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 |
options.scope | object |
|
A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) |
options.onDelete | string |
|
SET NULL if foreignKey allows nulls, CASCADE if otherwise |
options.onUpdate | string |
|
Set |
options.constraints | boolean |
|
Should on update and on delete constraints be enabled on the foreign key. |
Example:
User.hasMany(Profile) // This will add userId to the profile table
public static hasOne(target: Model, options: object): HasOne source
Creates an association between this (the source) and the provided target. The foreign key is added on the target.
Params:
Name | Type | Attribute | Description |
target | Model | Target model |
|
options | object |
|
hasOne association options |
options.hooks | boolean |
|
Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if |
options.as | string |
|
The alias of this model, in singular form. See also the |
options.foreignKey | string | object |
|
The name of the foreign key attribute in the target model or an object representing the type definition for the foreign column (see |
options.sourceKey | string |
|
The name of the attribute to use as the key for the association in the source table. Defaults to the primary key of the source table |
options.onDelete | string |
|
SET NULL if foreignKey allows nulls, CASCADE if otherwise |
options.onUpdate | string |
|
Sets 'ON UPDATE' |
options.constraints | boolean |
|
Should on update and on delete constraints be enabled on the foreign key. |
options.uniqueKey | string |
|
The custom name for unique constraint. |
Example:
User.hasOne(Profile) // This will add userId to the profile table
public static async increment(fields: string | Array | object, options: object): Promise<Model[], ?number> source
Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
SET column = column + X WHERE foo = 'bar'
query. To get the correct value after an increment into the Instance you should do a reload.
Params:
Name | Type | Attribute | Description |
fields | string | Array | object | If a string is provided, that column is incremented by the value of |
|
options | object | increment options |
|
options.where | object | conditions hash |
|
options.by | number |
|
The number to increment by |
options.silent | boolean |
|
If true, the updatedAt timestamp will not be updated. |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
Return:
Promise<Model[], ?number> | returns an array of affected rows and affected count with |
Example:
Model.increment('number', { where: { foo: 'bar' });
Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
// `by` is ignored, as each column has its own value
Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
See:
public static init(attributes: object, options: object): Model source
Initialize a model, representing a table in the DB, with attributes and options.
The table columns are defined by the hash that is given as the first argument. Each attribute of the hash represents a column.
Params:
Name | Type | Attribute | Description |
attributes | object | An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below: |
|
attributes.column | string | DataTypes | object | The description of a database column |
|
attributes.column.type | string | DataTypes | A string or a data type |
|
attributes.column.allowNull | boolean |
|
If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved. |
attributes.column.defaultValue | any |
|
A literal default value, a JavaScript function, or an SQL function (see |
attributes.column.unique | string | boolean |
|
If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index |
attributes.column.primaryKey | boolean |
|
If true, this attribute will be marked as primary key |
attributes.column.field | string |
|
If set, sequelize will map the attribute name to a different name in the database |
attributes.column.autoIncrement | boolean |
|
If true, this column will be set to auto increment |
attributes.column.autoIncrementIdentity | boolean |
|
If true, combined with autoIncrement=true, will use Postgres |
attributes.column.comment | string |
|
Comment for this column |
attributes.column.references | string | Model |
|
An object with reference configurations |
attributes.column.references.model | string | Model |
|
If this column references another table, provide it here as a Model, or a string |
attributes.column.references.key | string |
|
The column of the foreign table that this column references |
attributes.column.onUpdate | string |
|
What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION |
attributes.column.onDelete | string |
|
What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION |
attributes.column.get | Function |
|
Provide a custom getter for this column. Use |
attributes.column.set | Function |
|
Provide a custom setter for this column. Use |
attributes.column.validate | object |
|
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 |
options | object | These options are merged with the default define options provided to the Sequelize constructor |
|
options.sequelize | object | Define the sequelize instance to attach to the new Model. Throw error if none is provided. |
|
options.modelName | string |
|
Set name of the model. By default its same as Class name. |
options.defaultScope | object |
|
Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll |
options.scopes | object |
|
More scopes, defined in the same way as defaultScope above. See |
options.omitNull | boolean |
|
Don't persist null values. This means that all columns with null values will not be saved |
options.timestamps | boolean |
|
Adds createdAt and updatedAt timestamps to the model. |
options.paranoid | boolean |
|
Calling |
options.underscored | boolean |
|
Add underscored field to all attributes, this covers user defined attributes, timestamps and foreign keys. Will not affect attributes with explicitly set |
options.freezeTableName | boolean |
|
If freezeTableName is true, sequelize will not try to alter the model name to get the table name. Otherwise, the model name will be pluralized |
options.name | object |
|
An object with two attributes, |
options.name.singular | string |
|
Singular name for model |
options.name.plural | string |
|
Plural name for model |
options.indexes | Array<object> |
|
indexes definitions |
options.indexes[].name | string |
|
The name of the index. Defaults to model name + _ + fields concatenated |
options.indexes[].type | string |
|
Index type. Only used by mysql. One of |
options.indexes[].using | string |
|
The method to create the index by ( |
options.indexes[].operator | string |
|
Specify index operator. |
options.indexes[].unique | boolean |
|
Should the index by unique? Can also be triggered by setting type to |
options.indexes[].concurrently | boolean |
|
PostgresSQL will build the index without taking any write locks. Postgres only |
options.indexes[].fields | Array<string|object> |
|
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 |
options.createdAt | string | boolean |
|
Override the name of the createdAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting. |
options.updatedAt | string | boolean |
|
Override the name of the updatedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting. |
options.deletedAt | string | boolean |
|
Override the name of the deletedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting. |
options.tableName | string |
|
Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim |
options.schema | string |
|
schema |
options.engine | string |
|
Specify engine for model's table |
options.charset | string |
|
Specify charset for model's table |
options.comment | string |
|
Specify comment for model's table |
options.collate | string |
|
Specify collation for model's table |
options.initialAutoIncrement | string |
|
Set the initial AUTO_INCREMENT value for the table in MySQL. |
options.hooks | object |
|
An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, beforeSave, afterDestroy, afterUpdate, afterBulkCreate, afterSave, afterBulkDestroy and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions. |
options.validate | object |
|
An object of model wide validations. Validations have access to all model values via |
options.whereMergeStrategy | 'and' | 'overwrite' |
|
Specify the scopes merging strategy (default 'overwrite'). 'and' strategy will merge |
Example:
Project.init({
columnA: {
type: Sequelize.BOOLEAN,
validate: {
is: ['[a-z]','i'], // will only allow letters
max: 23, // only allow values <= 23
isIn: {
args: [['en', 'zh']],
msg: "Must be English or Chinese"
}
},
field: 'column_a'
// Other attributes here
},
columnB: Sequelize.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
}, {sequelize})
sequelize.models.modelName // The model will now be available in models under the class name
See:
- Model Basics guide
- Hooks guide
- Validations & Constraints guide
public static async max(field: string, options: object): Promise<*> source
Find the maximum value of field
See:
- Model.aggregate for options
public static async min(field: string, options: object): Promise<*> source
Find the minimum value of field
See:
- Model.aggregate for options
public static removeAttribute(attribute: string) source
Remove attribute from model definition
Params:
Name | Type | Attribute | Description |
attribute | string | name of attribute to remove |
public static async restore(options: object): Promise source
Restore multiple instances if paranoid
is enabled.
Params:
Name | Type | Attribute | Description |
options | object | restore options |
|
options.where | object |
|
Filter the restore |
options.hooks | boolean |
|
Run before / after bulk restore hooks? |
options.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 |
options.limit | number |
|
How many rows to undelete (only for mysql) |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.transaction | Transaction |
|
Transaction to run query under |
public static schema(schema: string, options: object): Model source
Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - "schema"."tableName"
,
while the schema will be prepended to the table name for mysql and sqlite - 'schema.tablename'
.
This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important
to call model.schema(schema, [options]).sync()
for each model to ensure the models are created in the correct schema.
If a single default schema per model is needed, set the options.schema='schema'
parameter during the define()
call
for the model.
Params:
Name | Type | Attribute | Description |
schema | string | The name of the schema |
|
options | object |
|
schema options |
options.schemaDelimiter | string |
|
The character(s) that separates the schema name from the table name |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
See:
- Sequelize#define for more information about setting a default schema.
public static scope(option: Array | object | string): Model source
Apply a scope created in define
to the model.
Params:
Name | Type | Attribute | Description |
option | Array | object | string |
|
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 |
Return:
Model | A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope. |
Example:
const Model = sequelize.define('model', attributes, {
defaultScope: {
where: {
username: 'dan'
},
limit: 12
},
scopes: {
isALie: {
where: {
stuff: 'cake'
}
},
complexFunction: function(email, accessLevel) {
return {
where: {
email: {
[Op.like]: email
},
access_level {
[Op.gte]: accessLevel
}
}
}
}
}
})
# As you have defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:
Model.findAll() // WHERE username = 'dan'
Model.findAll({ where: { age: { [Op.gt]: 12 } } }) // WHERE age > 12 AND username = 'dan'
Model.scope({ method: ['complexFunction', '[email protected]', 42]}).findAll()
// WHERE email like '[email protected]%' AND access_level >= 42
public static async sum(field: string, options: object): Promise<number> source
Find the sum of field
See:
- Model.aggregate for options
public static async sync(options: object): Promise<Model> source
Sync this Model to the DB, that is create the table.
Params:
Name | Type | Attribute | Description |
options | object |
|
sync options |
See:
- Sequelize#sync for options
public static async truncate(options: object): Promise source
Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
Params:
Name | Type | Attribute | Description |
options | object |
|
The options passed to Model.destroy in addition to truncate |
options.cascade | boolean | Function |
|
Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE. |
options.restartIdentity | boolean |
|
Automatically restart sequences owned by columns of the truncated table. |
options.transaction | Transaction |
|
Transaction to run query under |
options.logging | boolean | Function |
|
A function that logs sql queries, or false for no logging |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
See:
- Model.destroy for more information
public static async update(values: object, options: object): Promise<Array<number, number>> source
Update multiple instances that match the where options.
Params:
Name | Type | Attribute | Description |
values | object | hash of values to update |
|
options | object | update options |
|
options.where | object | Options to describe the scope of the search. |
|
options.paranoid | boolean |
|
If true, only non-deleted records will be updated. If false, both deleted and non-deleted records will be updated. Only applies if |
options.fields | Array |
|
Fields to update (defaults to all fields) |
options.validate | boolean |
|
Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation |
options.hooks | boolean |
|
Run before / after bulk update hooks? |
options.sideEffects | boolean |
|
Whether or not to update the side effects of any virtual setters. |
options.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 |
options.returning | boolean | Array |
|
If true, append RETURNING <model columns> to get back all defined values; if an array of column names, append RETURNING <columns> to get back specific columns (Postgres only) |
options.limit | number |
|
How many rows to update (only for mysql and mariadb, implemented as TOP(n) for MSSQL; for sqlite it is supported only when rowid is present) |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.transaction | Transaction |
|
Transaction to run query under |
options.silent | boolean |
|
If true, the updatedAt timestamp will not be updated. |
public static async upsert(values: object, options: object): Promise<Array<Model, boolean|null>> source
Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
Implementation details:
- MySQL - Implemented with ON DUPLICATE KEY UPDATE`
- PostgreSQL - Implemented with ON CONFLICT DO UPDATE. If update data contains PK field, then PK is selected as the default conflict key. Otherwise first unique constraint/index will be selected, which can satisfy conflict key requirements.
- SQLite - Implemented with ON CONFLICT DO UPDATE
- MSSQL - Implemented as a single query using
MERGE
andWHEN (NOT) MATCHED THEN
Note that Postgres/SQLite returns null for created, no matter if the row was created or updated
Params:
Name | Type | Attribute | Description |
values | object | hash of values to upsert |
|
options | object |
|
upsert options |
options.validate | boolean |
|
Run validations before the row is inserted |
options.fields | Array |
|
The fields to update if the record already exists. Defaults to all changed fields. If none of the specified fields are present on the provided |
options.hooks | boolean |
|
Run before / after upsert hooks? |
options.returning | boolean |
|
If true, fetches back auto generated values |
options.transaction | Transaction |
|
Transaction to run query under |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.benchmark | boolean |
|
Pass query execution time in milliseconds as second argument to logging function (options.logging). |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.conflictFields | Array<string> |
|
Optional override for the conflict fields in the ON CONFLICT part of the query. Only supported in Postgres >= 9.5 and SQLite >= 3.24.0 |
Return:
Promise<Array<Model, boolean|null>> | returns an array with two elements, the first being the new record and the second being |
Public Constructors
public constructor(values: object, options: object) source
Builds a new model instance.
Params:
Name | Type | Attribute | Description |
values | object |
|
an object of key value pairs |
options | object |
|
instance construction options |
options.raw | boolean |
|
If set to true, values will ignore field and virtual setters. |
options.isNewRecord | boolean |
|
Is this a new record |
options.include | Array |
|
an array of include options - Used to build prefetched/included model instances. See |
Public Members
Public Methods
public changed(key: string, value: any): boolean | Array source
If changed is called with a string it will return a boolean indicating whether the value of that key in dataValues
is different from the value in _previousDataValues
.
If changed is called without an argument, it will return an array of keys that have changed.
If changed is called without an argument and no keys have changed, it will return false
.
Please note that this function will return false
when a property from a nested (for example JSON) property
was edited manually, you must call changed('key', true)
manually in these cases.
Writing an entirely new object (eg. deep cloned) will be detected.
Params:
Name | Type | Attribute | Description |
key | string |
|
key to check or change status of |
value | any |
|
value to set |
Example:
```
const mdl = await MyModel.findOne();
mdl.myJsonField.a = 1;
console.log(mdl.changed()) => false
mdl.save(); // this will not save anything
mdl.changed('myJsonField', true);
console.log(mdl.changed()) => ['myJsonField']
mdl.save(); // will save
```
public async decrement(fields: string | Array | object, options: object): Promise source
Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
SET column = column - X
query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values.
Params:
Name | Type | Attribute | Description |
fields | string | Array | object | If a string is provided, that column is decremented by the value of |
|
options | object |
|
decrement options |
options.by | number |
|
The number to decrement by |
options.silent | boolean |
|
If true, the updatedAt timestamp will not be updated. |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.returning | boolean |
|
Append RETURNING * to get back auto generated values (Postgres only) |
Example:
instance.decrement('number') // decrement number by 1
instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
// decrement answer by 42, and tries by 1.
// `by` is ignored, since each column has its own value
instance.decrement({ answer: 42, tries: 1}, { by: 2 })
See:
public async destroy(options: object): Promise source
Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
Params:
Name | Type | Attribute | Description |
options | object |
|
destroy options |
options.force | boolean |
|
If set to true, paranoid models will actually be deleted |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
public equals(other: Model): boolean source
Check whether this and other
Instance refer to the same row
Params:
Name | Type | Attribute | Description |
other | Model | Other instance to compare against |
public equalsOneOf(others: Array<Model>): boolean source
Check if this is equal to one of others
by calling equals
public get(key: string, options: object): object | any source
If no key is given, returns all values of the instance, also invoking virtual getters.
If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
Params:
Name | Type | Attribute | Description |
key | string |
|
key to get value of |
options | object |
|
get options |
options.plain | boolean |
|
If set to true, included instances will be returned as plain objects |
options.raw | boolean |
|
If set to true, field and virtual setters will be ignored |
public getDataValue(key: string): any source
Get the value of the underlying data value
Params:
Name | Type | Attribute | Description |
key | string | key to look in instance data store |
Return:
any |
public async increment(fields: string | Array | object, options: object): Promise<Model> since 4.0.0 source
Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
SET column = column + X
query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values.
Params:
Name | Type | Attribute | Description |
fields | string | Array | object | If a string is provided, that column is incremented by the value of |
|
options | object |
|
options |
options.by | number |
|
The number to increment by |
options.silent | boolean |
|
If true, the updatedAt timestamp will not be updated. |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.returning | boolean |
|
Append RETURNING * to get back auto generated values (Postgres only) |
Example:
instance.increment('number') // increment number by 1
instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
// increment answer by 42, and tries by 1.
// `by` is ignored, since each column has its own value
instance.increment({ answer: 42, tries: 1}, { by: 2 })
See:
public isSoftDeleted(): boolean source
Helper method to determine if a instance is "soft deleted". This is
particularly useful if the implementer renamed the deletedAt
attribute
to something different. This method requires paranoid
to be enabled.
public previous(key: string): any | Array<any> source
Returns the previous value for key from _previousDataValues
.
If called without a key, returns the previous values for all values which have changed
Params:
Name | Type | Attribute | Description |
key | string |
|
key to get previous value of |
public async reload(options: object): Promise<Model> source
Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
This is different from doing a find(Instance.id)
, because that would create and return a new instance. With this method,
all references to the Instance are updated with the new data and no new objects are created.
See:
public async restore(options: object): Promise source
Restore the row corresponding to this instance. Only available for paranoid models.
Params:
Name | Type | Attribute | Description |
options | object |
|
restore options |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.transaction | Transaction |
|
Transaction to run query under |
public async save(options: object): Promise<Model> source
Validates this instance, and if the validation passes, persists it to the database.
Returns a Promise that resolves to the saved instance (or rejects with a Sequelize.ValidationError
, which will have a property for each of the fields for which the validation failed, with the error message for that field).
This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.
This method is not aware of eager loaded associations. In other words, if some other model instance (child) was eager loaded with this instance (parent), and you change something in the child, calling save()
will simply ignore the change that happened on the child.
Params:
Name | Type | Attribute | Description |
options | object |
|
save options |
options.fields | string[] |
|
An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. |
options.silent | boolean |
|
If true, the updatedAt timestamp will not be updated. |
options.validate | boolean |
|
If false, validations won't be run. |
options.hooks | boolean |
|
Run before and after create / update + validate hooks |
options.logging | Function |
|
A function that gets executed while running the query to log the sql. |
options.transaction | Transaction |
|
Transaction to run query under |
options.searchPath | string |
|
An optional parameter to specify the schema search_path (Postgres only) |
options.returning | boolean |
|
Append RETURNING * to get back auto generated values (Postgres only) |
public set(key: string | object, value: any, options: object): Model source
Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call save
).
In its most basic form set
will update a value stored in the underlying dataValues
object. However, if a custom setter function is defined for the key, that function
will be called instead. To bypass the setter, you can pass raw: true
in the options object.
If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
When set is called, the previous value of the field is stored and sets a changed flag(see changed
).
Set can also be used to build instances for associations, if you have values for those. When using set with associations you need to make sure the property key matches the alias of the association while also making sure that the proper include options have been set (from .build() or .findOne())
If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
Params:
Name | Type | Attribute | Description |
key | string | object | key to set, it can be string or object. When string it will set that key, for object it will loop over all object properties nd set them. |
|
value | any | value to set |
|
options | object |
|
set options |
options.raw | boolean |
|
If set to true, field and virtual setters will be ignored |
options.reset | boolean |
|
Clear all previously set data values |
See:
- Model.findAll for more information about includes
public setDataValue(key: string, value: any) source
Update the underlying data value
Params:
Name | Type | Attribute | Description |
key | string | key to set in instance data store |
|
value | any | new value for given key |
public toJSON(): object source
Convert the instance to a JSON representation.
Proxies to calling get
with no keys.
This means get all values gotten from the DB, and apply all custom getters.
See:
public async update(values: object, options: object): Promise<Model> source
This is the same as calling set
and then calling save
but it only saves the
exact values passed to it, making it more atomic and safer.
See:
public async validate(options: object): Promise source
Validate the attributes of this instance according to validation rules set in the model definition.
The promise fulfills if and only if validation successful; otherwise it rejects an Error instance containing { field name : [error msgs] } entries.
Params:
Name | Type | Attribute | Description |
options | object |
|
Options that are passed to the validator |
options.skip | Array |
|
An array of strings. All properties that are in this array will not be validated |
options.fields | Array |
|
An array of strings. Only the properties that are in this array will be validated |
options.hooks | boolean |
|
Run before and after validate hooks |