Class Model

View code

A Model represents a table in the database. Sometimes you might also see it referred to as model, or simply as factory.This class should not be instantiated directly, it is created using sequelize.define, and already created models can be loaded using sequelize.import

Mixes:

  • Hooks
  • Associations

removeAttribute([attribute])

View code

Remove attribute from model definition

Params:

NameTypeDescription
[attribute]String

sync() -> Promise.<this>

View code

Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)

See:


drop([options]) -> Promise

View code

Drop the table represented by this Model

Params:

NameTypeDescription
[options]Object
[options.cascade=false]BooleanAlso drop all objects depending on this table, such as views. Only works in postgres
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).

schema(schema, [options]) -> this

View code

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

Params:

NameTypeDescription
schemaStringThe name of the schema
[options]Object
[options.schemaDelimiter='.']StringThe character(s) that separates the schema name from the table name
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).

getTableName([options]) -> String|Object

View code

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 and delimiter properties.

Params:

NameTypeDescription
[options]ObjectThe 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)
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).

unscoped() -> Model

View code


addScope(name, scope, [options])

View code

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

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

Params:

NameTypeDescription
nameStringThe name of the scope. Use defaultScope to override the default scope
scopeObject | Function
[options]Object
[options.override=false]Boolean

scope(options*) -> Model

View code

Apply a scope created in define to the model. First let's look at how to create scopes:

  1. var Model = sequelize.define('model', attributes, {
  2. defaultScope: {
  3. where: {
  4. username: 'dan'
  5. },
  6. limit: 12
  7. },
  8. scopes: {
  9. isALie: {
  10. where: {
  11. stuff: 'cake'
  12. }
  13. },
  14. complexFunction: function(email, accessLevel) {
  15. return {
  16. where: {
  17. email: {
  18. $like: email
  19. },
  20. accesss_level {
  21. $gte: accessLevel
  22. }
  23. }
  24. }
  25. }
  26. }
  27. })

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:

  1. Model.findAll() // WHERE username = 'dan'
  2. Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'

To invoke scope functions you can do:

  1. Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
  2. // WHERE email like 'dan@sequelize.com%' AND access_level >= 42

Params:

NameTypeDescription
options*Array | Object | StringThe 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.

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


findAll([options]) -> Promise.<Array.<Instance>>

View code

Search for multiple instances.

Simple search using AND and =

  1. Model.findAll({
  2. where: {
  3. attr1: 42,
  4. attr2: 'cake'
  5. }
  6. })
  1. WHERE attr1 = 42 AND attr2 = 'cake'

Using greater than, less than etc.

  1. Model.findAll({
  2. where: {
  3. attr1: {
  4. gt: 50
  5. },
  6. attr2: {
  7. lte: 45
  8. },
  9. attr3: {
  10. in: [1,2,3]
  11. },
  12. attr4: {
  13. ne: 5
  14. }
  15. }
  16. })
  1. WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5

Possible options are: $ne, $in, $not, $notIn, $gte, $gt, $lte, $lt, $like, $ilike/$iLike, $notLike, $notILike, '..'/$between, '!..'/$notBetween, '&&'/$overlap, '@>'/$contains, '<@'/$contained

Queries using OR

  1. Model.findAll({
  2. where: {
  3. name: 'a project',
  4. $or: [
  5. {id: [1, 2, 3]},
  6. {
  7. $and: [
  8. {id: {gt: 10}},
  9. {id: {lt: 100}}
  10. ]
  11. }
  12. ]
  13. }
  14. });
  1. WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));

The success listener is called with an array of instances if the query succeeds.

See:

Params:

NameTypeDescription
[options]ObjectA hash of options to describe the scope of the search
[options.where]ObjectA hash of attributes to describe your search. See above for examples.
[options.attributes]Array.<String> | ObjectA list of the attributes that you want to select, or an object with include and exclude keys. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the returned instance
[options.attributes.include]Array.<String>Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. { attributes: { include: [[sequelize.fn('COUNT', sequelize.col('id')), 'total']] }
[options.attributes.exclude]Array.<String>Select all the attributes of the model, except some few. Useful for security purposes e.g. { attributes: { exclude: ['password'] } }
[options.paranoid=true]BooleanIf true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if options.paranoid is true for the model.
[options.include]Array.<Object | Model>A list of associations to eagerly load using a left join. Supported is either { include: [ Model1, Model2, …]} or { include: [{ model: Model1, as: 'Alias' }]}. If your association are set up with an as (eg. X.hasMany(Y, { as: 'Z }, you need to specify Z in the as attribute when eager loading Y).
[options.include[].model]ModelThe model you want to eagerly load
[options.include[].as]StringThe alias of the relation, in case the model you want to eagerly load is aliased. For hasOne / belongsTo, this should be the singular name, and for hasMany, it should be the plural
[options.include[].association]AssociationThe association you want to eagerly load. (This can be used instead of providing a model/as pair)
[options.include[].where]ObjectWhere clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set required: false
[options.include[].or=false]BooleanWhether to bind the ON and WHERE clause together by OR instead of AND.
[options.include[].on]ObjectSupply 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]BooleanIf true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if include.where is set, false otherwise.
[options.include[].separate]BooleanIf true, runs a separate query to fetch the associated instances, only supported for hasMany associations
[options.include[].limit]NumberLimit the joined rows, only supported with include.separate=true
[options.include[].through.where]ObjectFilter on the join model for belongsToMany relations
[options.include[].through.attributes]ArrayA list of attributes to select from the join model for belongsToMany relations
[options.include[].include]Array.<Object | Model>Load further nested related models
[options.order]String | Array | Sequelize.fnSpecifies 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.
[options.limit]Number
[options.offset]Number
[options.transaction]TransactionTransaction to run query under
[options.lock]String | ObjectLock 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
[options.raw]BooleanReturn raw result. See sequelize.query for more information.
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.having]Object
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)
[options.rejectOnEmpty=false]Boolean | ErrorThrows an error when no records found

Aliases: all


findById(id, [options]) -> Promise.<Instance>

View code

Search for a single instance by its primary key.

See:

Params:

NameTypeDescription
idNumber | String | BufferThe value of the desired instance's primary key.
[options]Object
[options.transaction]TransactionTransaction to run query under
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

Aliases: findByPrimary


findOne([options]) -> Promise.<Instance>

View code

Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.

See:

Params:

NameTypeDescription
[options]ObjectA hash of options to describe the scope of the search
[options.transaction]TransactionTransaction to run query under
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

Aliases: find


aggregate(field, aggregateFunction, [options]) -> Promise.<options.dataType|object>

View code

Run an aggregation method on the specified field

Params:

NameTypeDescription
fieldStringThe field to aggregate over. Can be a field name or *
aggregateFunctionStringThe function to use for aggregation, e.g. sum, max etc.
[options]ObjectQuery options. See sequelize.query for full options
[options.where]ObjectA hash of search attributes.
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.dataType]DataType | StringThe type of the result. If field is a field in this Model, the default will be the type of that field, otherwise defaults to float.
[options.distinct]booleanApplies DISTINCT to the field being aggregated over
[options.transaction]TransactionTransaction to run query under
[options.plain]BooleanWhen true, the first returned value of aggregateFunction is cast to dataType and returned. If additional attributes are specified, along with group clauses, set plain to false to return all values of all returned rows. Defaults to true

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


count([options]) -> Promise.<Integer>

View code

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:

NameTypeDescription
[options]Object
[options.where]ObjectA hash of search attributes.
[options.include]ObjectInclude options. See find for details
[options.distinct]booleanApply COUNT(DISTINCT(col)) on primary key, Model.aggregate should be used for other columns
[options.attributes]ObjectUsed in conjunction with group
[options.group]ObjectFor creating complex counts. Will return multiple rows as needed.
[options.transaction]TransactionTransaction to run query under
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

findAndCount([findOptions]) -> Promise.<Object>

View code

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

  1. Model.findAndCountAll({
  2. where: ...,
  3. limit: 12,
  4. offset: 12
  5. }).then(function (result) {
  6. ...
  7. })

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:

  1. User.findAndCountAll({
  2. include: [
  3. { model: Profile, required: true}
  4. ],
  5. distinct: true,
  6. limit 3
  7. });

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:

Params:

NameTypeDescription
[findOptions]ObjectSee findAll

Aliases: findAndCountAll


max(field, [options]) -> Promise.<Any>

View code

Find the maximum value of field

See:

Params:

NameTypeDescription
fieldString
[options]ObjectSee aggregate

min(field, [options]) -> Promise.<Any>

View code

Find the minimum value of field

See:

Params:

NameTypeDescription
fieldString
[options]ObjectSee aggregate

sum(field, [options]) -> Promise.<Number>

View code

Find the sum of field

See:

Params:

NameTypeDescription
fieldString
[options]ObjectSee aggregate

build(values, [options]) -> Instance

View code

Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.

Params:

NameTypeDescription
valuesObject
[options]Object
[options.raw=false]BooleanIf set to true, values will ignore field and virtual setters.
[options.isNewRecord=true]Boolean
[options.include]Arrayan array of include options - Used to build prefetched/included model instances. See set

create(values, [options]) -> Promise.<Instance>

View code

Builds a new model instance and calls save on it.

See:

Params:

NameTypeDescription
valuesObject
[options]Object
[options.raw=false]BooleanIf set to true, values will ignore field and virtual setters.
[options.isNewRecord=true]Boolean
[options.fields]ArrayIf set, only columns matching those in fields will be saved
[options.include]Arrayan array of include options - Used to build prefetched/included model instances
[options.onDuplicate]String
[options.transaction]TransactionTransaction to run query under
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

findOrInitialize -> Promise.<Instance, initialized>

View code

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

Params:

NameTypeDescription
optionsObject
options.whereObjectA hash of search attributes.
[options.defaults]ObjectDefault values to use if building a new instance
[options.transaction]ObjectTransaction to run query under
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).

Aliases: findOrBuild


findOrCreate(options) -> Promise.<Instance, created>

View code

Find a row that matches the query, or build and save the row if none is foundThe successful result of the promise will be (instance, created) - Make sure to use .spread()

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.

See:

Params:

NameTypeDescription
optionsObject
options.whereObjectwhere A hash of search attributes.
[options.defaults]ObjectDefault values to use if creating a new instance
[options.transaction]TransactionTransaction to run query under

findCreateFind(options) -> Promise.<Instance, created>

View code

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

See:

Params:

NameTypeDescription
optionsObject
options.whereObjectwhere A hash of search attributes.
[options.defaults]ObjectDefault values to use if creating a new instance

upsert(values, [options]) -> Promise.<created>

View code

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 queries INSERT; UPDATE. This means that the update is executed regardless of whether the row already existed or not
  • MSSQL - Implemented as a single query using MERGE and WHEN (NOT) MATCHED THENNote that SQLite returns undefined 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.

Params:

NameTypeDescription
valuesObject
[options]Object
[options.validate=true]BooleanRun validations before the row is inserted
[options.fields=Object.keys(this.attributes)]ArrayThe fields to insert / update. Defaults to all fields
[options.transaction]TransactionTransaction to run query under
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

Returns: Returns a boolean indicating whether the row was created or updated.Aliases: insertOrUpdate


bulkCreate(records, [options]) -> Promise.<Array.<Instance>>

View code

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

Params:

NameTypeDescription
recordsArrayList of objects (key/value pairs) to create instances from
[options]Object
[options.fields]ArrayFields to insert (defaults to all fields)
[options.validate=false]BooleanShould each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
[options.hooks=true]BooleanRun before / after bulk create hooks?
[options.individualHooks=false]BooleanRun before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
[options.ignoreDuplicates=false]BooleanIgnore duplicate values for primary keys? (not supported by postgres)
[options.updateOnDuplicate]ArrayFields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.
[options.transaction]TransactionTransaction to run query under
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.returning=false]BooleanAppend RETURNING * to get back auto generated values (Postgres only)
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

truncate([options]) -> Promise

View code

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

See:

Params:

NameTypeDescription
[options]objectThe options passed to Model.destroy in addition to truncate
[options.transaction]Boolean | functionTransaction to run query under
[options.cascadeBoolean | function= false] Only used in conjunction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
[options.transaction]TransactionTransaction to run query under
[options.logging]Boolean | functionA function that logs sql queries, or false for no logging
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.searchPath=DEFAULT]StringAn optional parameter to specify the schema search_path (Postgres only)

destroy(options) -> Promise.<Integer>

View code

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

Params:

NameTypeDescription
optionsObject
[options.where]ObjectFilter the destroy
[options.hooks=true]BooleanRun before / after bulk destroy hooks?
[options.individualHooks=false]BooleanIf set to true, destroy will SELECT all records matching the where parameter and will execute before / after destroy hooks on each row
[options.limit]NumberHow many rows to delete
[options.force=false]BooleanDelete instead of setting deletedAt to current timestamp (only applicable if paranoid is enabled)
[options.truncate=false]BooleanIf 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=false]BooleanOnly 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=false]BooleanOnly used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table.
[options.transaction]TransactionTransaction to run query under
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).

Returns: The number of destroyed rows


restore(options) -> Promise.<undefined>

View code

Restore multiple instances if paranoid is enabled.

Params:

NameTypeDescription
optionsObject
[options.where]ObjectFilter the restore
[options.hooks=true]BooleanRun before / after bulk restore hooks?
[options.individualHooks=false]BooleanIf set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row
[options.limit]NumberHow many rows to undelete
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.transaction]TransactionTransaction to run query under

update(values, options) -> Promise.<Array.<affectedCount, affectedRows>>

View code

Update multiple instances that match the where options. The promise returns an array with one or two elements. The first element is always the numberof affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true.)

Params:

NameTypeDescription
valuesObject
optionsObject
options.whereObjectOptions to describe the scope of the search.
[options.fields]ArrayFields to update (defaults to all fields)
[options.validate=true]BooleanShould each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
[options.hooks=true]BooleanRun before / after bulk update hooks?
[options.sideEffects=true]BooleanWhether or not to update the side effects of any virtual setters.
[options.individualHooks=false]BooleanRun 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=false]BooleanReturn the affected rows (only for postgres)
[options.limit]NumberHow many rows to update (only for mysql and mariadb)
[options.logging=false]FunctionA function that gets executed while running the query to log the sql.
[options.benchmark=false]BooleanPass query execution time in milliseconds as second argument to logging function (options.logging).
[options.transaction]TransactionTransaction to run query under
[options.silent=false]BooleanIf true, the updatedAt timestamp will not be updated.

describe() -> Promise

View code

Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.


This document is automatically generated based on source code comments. Please do not edit it directly, as your changes will be ignored. Please write on IRC, open an issue or a create a pull request if you feel something can be improved. For help on how to write source code documentation see JSDoc and dox