Class Sequelize

View code
This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:

var Sequelize = require('sequelize');

In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.


new Sequelize(database, [username=null], [password=null], [options={}])

View code
Instantiate sequelize with name of database, username and password

Example usage

// without password and options
var sequelize = new Sequelize('database', 'username')
// without options
var sequelize = new Sequelize('database', 'username', 'password')
// without password / with blank password
var sequelize = new Sequelize('database', 'username', null, {})
// with password and options
var sequelize = new Sequelize('my_database', 'john', 'doe', {})
// with uri (see below)
var sequelize = new Sequelize('mysql://localhost:3306/database', {})

Params:

Name Type Description
database String The name of the database
[username=null] String The username which is used to authenticate against the database.
[password=null] String The password which is used to authenticate against the database.
[options={}] Object An object with options.
[options.dialect='mysql'] String The dialect you of the database you are connecting to. One of mysql, postgres, sqlite, mariadb, and mssql
[options.dialectModulePath=null] String If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
[options.dialectOptions] Object An object of additional options, which are passed directly to the connection library
[options.storage] String Only used by sqlite. Defaults to ':memory:'
[options.host='localhost'] String The host of the relational database.
[options.port=] Integer The port of the relational database.
[options.protocol='tcp'] String The protocol of the relational database.
[options.define={}] Object Default options for model definitions. See sequelize.define for options
[options.query={}] Object Default options for sequelize.query
[options.set={}] Object Default options for sequelize.set
[options.sync={}] Object Default options for sequelize.sync
[options.timezone='+00:00'] String The timezone used when converting a date from the database into a javascript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM.
[options.logging=console.log] Function A function that gets executed everytime Sequelize would log something.
[options.omitNull=false] Boolean A flag that defines if null values should be passed to SQL queries or not.
[options.queue=true] Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all queries will be executed immediately.
[options.maxConcurrentQueries=50] Integer The maximum number of queries that should be executed at once if queue is true.
[options.native=false] Boolean A flag that defines if native library shall be used or not. Currently only has an effect for postgres
[options.replication=false] Boolean Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: host, port, username, password, database
[options.pool={}] Object Should sequelize use a connection pool. Default is true
[options.pool.maxConnections] Integer
[options.pool.minConnections] Integer
[options.pool.maxIdleTime] Integer The maximum time, in milliseconds, that a connection can be idle before being released
[options.pool.validateConnection] Function A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
[options.quoteIdentifiers=true] Boolean Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them.

new Sequelize(uri, [options={}])

View code
Instantiate sequlize with an URI

Params:

Name Type Description
uri String A full database URI
[options={}] object See above for possible options

models

View code
Models are stored here under the name given to sequelize.define


Sequelize

View code
A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.

See:


Utils

View code
A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in your project.

See:


Promise

View code
A modified version of bluebird promises, that allows listening for sql events

See:


Validator

View code
Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor.

See:


Transaction

View code
A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction

See:


Instance

View code
A reference to the sequelize instance class.

See:


Error

View code
A general error class

See:


ValidationError

View code
Emitted when a validation fails

See:


ValidationErrorItem

View code
Describes a validation error on an instance path

See:


DatabaseError

View code
A base class for all database related errors.

See:


TimeoutError

View code
Thrown when a database query times out because of a deadlock

See:


UniqueConstraintError

View code
Thrown when a unique constraint is violated in the database

See:


ForeignKeyConstraintError

View code
Thrown when a foreign key constraint is violated in the database

See:


ConnectionError

View code
A base class for all connection related errors.

See:


ConnectionRefusedError

View code
Thrown when a connection to a database is refused

See:


AccessDeniedError

View code
Thrown when a connection to a database is refused due to insufficient access

See:


HostNotFoundError

View code
Thrown when a connection to a database has a hostname that was not found

See:


HostNotReachableError

View code
Thrown when a connection to a database has a hostname that was not reachable

See:


InvalidConnectionError

View code
Thrown when a connection to a database has invalid values for any of the connection parameters

See:


ConnectionTimedOutError

View code
Thrown when a connection to a database times out

See:


getDialect() -> String

View code
Returns the specified dialect.

Returns: The specified dialect.


getQueryInterface() -> QueryInterface

View code
Returns an instance of QueryInterface.

See:

Returns: An instance (singleton) of QueryInterface.


getMigrator([options={}], [force=false]) -> Migrator

View code
Returns an instance (singleton) of Migrator.

See:

Params:

Name Type Description
[options={}] Object See Migrator for options
[force=false] Boolean A flag that defines if the migrator should get instantiated or not.

Returns: An instance of Migrator.


define(modelName, attributes, [options]) -> Model

View code
Define a new model, representing a table in the DB.

The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:

sequelize.define('modelName', {
    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.models.modelName // The model will now be available in models under the name given to define

As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.

For a list of possible data types, see http://sequelizejs.com/docs/latest/models#data-types

For more about getters and setters, see http://sequelizejs.com/docs/latest/models#getters---setters

For more about instance and class methods, see http://sequelizejs.com/docs/latest/models#expansion-of-models

For more about validation, see http://sequelizejs.com/docs/latest/models#validations

See:

Params:

Name Type Description
modelName String The name of the model. The model will be stored in sequelize.models under this name
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 | DataType Object
attributes.column.type String | DataType A string or a data type
[attributes.column.allowNull=true] 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=null] Any A literal default value, a javascript function, or an SQL function (see sequelize.fn)
[attributes.column.unique=false] 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=false] Boolean
[attributes.column.field=null] String If set, sequelize will map the attribute name to a different name in the database
[attributes.column.autoIncrement=false] Boolean
[attributes.column.comment=null] String
[attributes.column.references] String | Model If this column references another table, provide it here as a Model, or a string
[attributes.column.referencesKey='id'] 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 this.getDataValue(String) to manipulate the underlying values.
[attributes.column.set] Function Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values.
[attributes.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 DAOValidator property for more details), or a custom validation function. Custom validation functions are called with the value of the field, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, the callback should be called with the error text.
[options] Object These options are merged with the default define options provided to the Sequelize constructor
[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 Model.scope for more information about how scopes are defined, and what you can do with them
[options.omitNull] Boolean Don't persits null values. This means that all columns with null values will not be saved
[options.timestamps=true] Boolean Adds createdAt and updatedAt timestamps to the model.
[options.paranoid=false] Boolean Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs timestamps=true to work
[options.underscored=false] Boolean Converts all camelCased columns to underscored if true
[options.underscoredAll=false] Boolean Converts camelCased model names to underscored tablenames if true
[options.freezeTableName=false] Boolean If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the dao name will be pluralized
[options.name] Object An object with two attributes, singular and plural, which are used when this model is associated to others.
[options.name.singular=inflection.singularize(modelName)] String
[options.name.plural=inflection.pluralize(modelName)] String
[options.indexes] Array<Object>
[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 UNIQUE, FULLTEXT and SPATIAL
[options.indexes[].method] String The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN.
[options.indexes[].unique=false] Boolean Should the index by unique? Can also be triggered by setting type to UNIQUE
[options.indexes[].concurrently=false] Boolean PostgreSQL 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, or an object with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the direction the column should be sorted in), collate (the collation (sort order) for the column)
[options.createdAt] String | Boolean Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true
[options.updatedAt] String | Boolean Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true
[options.deletedAt] String | Boolean Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true
[options.tableName] String Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim
[options.getterMethods] Object Provide getter functions that work like those defined per column. If you provide a getter method with the same name as a column, it will be used to access the value of that column. If you provide a name that does not match a column, this function will act as a virtual getter, that can fetch multiple other values
[options.setterMethods] Object Provide setter functions that work like those defined per column. If you provide a setter method with the same name as a column, it will be used to update the value of that column. If you provide a name that does not match a column, this function will act as a virtual setter, that can act on and set other values, but will not be persisted
[options.instanceMethods] Object Provide functions that are added to each instance (DAO). If you override methods provided by sequelize, you can access the original method using this.constructor.super_.prototype, e.g. this.constructor.super_.prototype.toJSON.apply(this, arguments)
[options.classMethods] Object Provide functions that are added to the model (Model). If you override methods provided by sequelize, you can access the original method using this.constructor.prototype, e.g. this.constructor.prototype.find.apply(this, arguments)
[options.schema='public'] String
[options.engine] String
[options.charset] String
[options.comment] String
[options.collate] String
[options.hooks] Object An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory 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 this. If the validator function takes an argument, it is asumed to be async, and is called with a callback that accepts an optional error.

model(modelName) -> Model

View code
Fetch a DAO factory which is already defined

Params:

Name Type Description
modelName String The name of a model defined with Sequelize.define

isDefined(modelName) -> Boolean

View code
Checks whether a model with the given name is defined

Params:

Name Type Description
modelName String The name of a model defined with Sequelize.define

import(path) -> Model

View code
Imports a model defined in another file

Imported models are cached, so multiple calls to import with the same path will not load the file multiple times

See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a short example of how to define your models in separate files so that they can be imported by sequelize.import

Params:

Name Type Description
path String The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file

query(sql, [callee], [options={}], [replacements]) -> Promise

View code
Execute a query on the DB, with the posibility to bypass all the sequelize goodness.

If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.

See:

Params:

Name Type Description
sql String
[callee] Instance If callee is provided, the returned data will be put into the callee
[options={}] Object Query options.
[options.raw] Boolean If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
[options.transaction=null] Transaction The transaction that the query should be executed under
[options.type='SELECT'] String The type of query you are executing. The query type affects how results are formatted before they are passed back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options are SELECT, BULKUPDATE and BULKDELETE
[options.nest=false] Boolean If true, transforms objects with . separated property names into nested objects using dottie.js. For example { 'user.username': 'john' } becomes { user: { username: 'john' }}
[replacements] Object | Array Either an object of named parameter replacements in the format :param or an array of unnamed replacements to replace ? in your SQL.

set(variables, options) -> Promise

View code
Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
Only works for MySQL.

Params:

Name Type Description
variables Object Object with multiple variables.
options Object Query options.
options.transaction Transaction The transaction that the query should be executed under

createSchema(schema) -> Promise

View code
Create a new database schema.

Note,that this is a schema in the postgres sense of the word,
not a database table. In mysql and sqlite, this command will do nothing.

See:

Params:

Name Type Description
schema String Name of the schema

showAllSchemas() -> Promise

View code
Show all defined schemas

Note,that this is a schema in the postgres sense of the word,
not a database table. In mysql and sqlite, this will show all tables.


dropSchema(schema) -> Promise

View code
Drop a single schema

Note,that this is a schema in the postgres sense of the word,
not a database table. In mysql and sqlite, this drop a table matching the schema name

Params:

Name Type Description
schema String Name of the schema

dropAllSchemas() -> Promise

View code
Drop all schemas

Note,that this is a schema in the postgres sense of the word,
not a database table. In mysql and sqlite, this is the equivalent of drop all tables.


sync([options={}]) -> Promise

View code
Sync all defined DAOs to the DB.

Params:

Name Type Description
[options={}] Object
[options.force=false] Boolean If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table
[options.match] RegEx Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
[options.logging=console.log] Boolean | function A function that logs sql queries, or false for no logging
[options.schema='public'] String The schema that the tables should be created in. This can be overriden for each table in sequelize.define

drop(options) -> Promise

View code
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model

See:

Params:

Name Type Description
options object The options passed to each call to Model.drop

authenticate() -> Promise

View code
Test the connection by trying to authenticate

Aliases: validate


fn (fn, args) -> Sequelize.fn

View code
Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
If you want to refer to columns in your function, you should use sequelize.col, so that the columns are properly interpreted as columns and not a strings.

Convert a user's username to upper case

instance.updateAttributes({
  username: self.sequelize.fn('upper', self.sequelize.col('username'))
})

See:

Params:

Name Type Description
fn String The function you want to call
args any All further arguments will be passed as arguments to the function

col(col) -> Sequelize.col

View code
Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since raw string arguments to fn will be escaped.

See:

Params:

Name Type Description
col String The name of the column

cast(val, type) -> Sequelize.cast

View code
Creates a object representing a call to the cast function.

Params:

Name Type Description
val any The value to cast
type String The type to cast it to

literal(val) -> Sequelize.literal

View code
Creates a object representing a literal, i.e. something that will not be escaped.

Params:

Name Type Description
val any

Aliases: asIs


and(args) -> Sequelize.and

View code
An AND query

See:

Params:

Name Type Description
args String | Object Each argument will be joined by AND

or(args) -> Sequelize.or

View code
An OR query

See:

Params:

Name Type Description
args String | Object Each argument will be joined by OR

json(conditions, [value]) -> Sequelize.json

View code
Creates an object representing nested where conditions for postgres's json data-type.

See:

Params:

Name Type Description
conditions String | Object A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
[value] String | Number Boolean

where(attr, [comparator='='], logic) -> Sequelize.where

View code
A way of specifying attr = condition.

The attr can either be an object taken from Model.rawAttributes (for example Model.rawAttributes.id or Model.rawAttributes.name). The
attribute should be defined in your model definition. The attribute can also be an object from one of the sequelize utility functions (sequelize.fn, sequelize.col etc.)

For string attributes, use the regular { where: { attr: something }} syntax. If you don't want your string to be escaped, use sequelize.literal.

See:

Params:

Name Type Description
attr Object The attribute, which can be either an attribute object from Model.rawAttributes or a sequelize object, for example an instance of sequelize.fn. For simple string attributes, use the POJO syntax
[comparator='='] string
logic String | Object The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.)

Aliases: condition


transaction([options={}]) -> Promise

View code
Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction

sequelize.transaction().then(function (t) {
  return User.find(..., { transaction: t}).then(function (user) {
    return user.updateAttributes(..., { transaction: t});
  })
  .then(t.commit.bind(t))
  .catch(t.rollback.bind(t));
})

A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:

sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then()
  return User.find(..., { transaction: t}).then(function (user) {
    return user.updateAttributes(..., { transaction: t});
  });
}).then(function () {
  // Commited
}).catch(function (err) {
  // Rolled back
  console.error(err);
});

See:

Params:

Name Type Description
[options={}] Object
[options.autocommit=true] Boolean
[options.isolationLevel='REPEATABLE String READ'] See Sequelize.Transaction.ISOLATION_LEVELS for possible options

Class Model

View code
A Model represents a table in the database. Sometimes you might also see it refererred 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:

Name Type Description
[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:

Name Type Description
[options] Object
[options.cascade=false] Boolean Also drop all objects depending on this table, such as views. Only works in postgres

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:

Name Type Description
schema String The name of the schema
[options] Object
[options.schemaDelimiter='.'] String The character(s) that separates the schema name from the table name

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:

Name Type Description
options Object The hash of options from any query. You can use one model to access tables with matching schemas by overriding getTableName and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)

scope(options*) -> Model

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

var Model = sequelize.define('model', attributes, {
  defaultScope: {
    where: {
      username: 'dan'
    },
    limit: 12
  },
  scopes: {
    isALie: {
      where: {
        stuff: 'cake'
      }
    },
    complexFunction: function(email, accessLevel) {
      return {
        where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
      }
    },
  }
})

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

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

To invoke scope functions you can do:

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

Params:

Name Type Description
options* Array | Object String

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], [queryOptions]) -> Promise<Array<Instance>>

View code
Search for multiple instances.

Simple search using AND and =

Model.find({
  where: {
    attr1: 42,
    attr2: 'cake'
  }
})
WHERE attr1 = 42 AND attr2 = 'cake'

Using greater than, less than etc.

Model.find({
  where: {
    attr1: {
      gt: 50
    },
    attr2: {
      lte: 45
    },
    attr3: {
      in: [1,2,3]
    },
    attr4: {
      ne: 5
    }
  }
})
WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5

Possible options are: gt, gte, lt, lte, ne, between/.., nbetween/notbetween/!.., in, not, like, nlike/notlike

Queries using OR

Model.find({
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { gt: 10 } }
    )
  )
})
WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)

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

See:

Params:

Name Type 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> A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the returned instance
[options.paranoid=true] Boolean If false, will include columns which have a non-null deletedAt column.
[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] 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 aliassed. For hasOne / belongsTo, this should be the singular name, and for hasMany, it should be the plural
[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 required: false
[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 include.where is set, false otherwise.
[options.include[].include] Array<Object | Model> Load further nested related models
[options.order] String | Array Sequelize.fn
[options.limit] Number
[options.offset] Number
[options.transaction] Transaction
[queryOptions] Object Set the query options, e.g. raw, specifying that you want raw data instead of built Instances. See sequelize.query for options
[queryOptions.lock] String Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. See transaction.LOCK for an example

Aliases: all


findOne([options], [queryOptions]) -> 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:

Name Type Description
[options] Object | Number A hash of options to describe the scope of the search, or a number to search by id.
[options.transaction] Transaction
[queryOptions] Object

Aliases: find


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

View code
Run an aggregation method on the specified field

Params:

Name Type Description
field String The field 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.dataType] DataType | String The type of the result. If field is a field in this Model, the default will be the type of that field, otherwise defaults to float.
[options.distinct] boolean Applies DISTINCT to the field being aggregated over
[options.transaction] Transaction

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:

Name Type Description
[options] Object
[options.include] Object Include options. See find for details
[options.distinct] boolean Appliy COUNT(DISTINCT(col))

findAndCount([findOptions], [queryOptions]) -> 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 usefull for paging

Model.findAndCountAll({
  where: ...,
  limit: 12,
  offset: 12
}).success(function (result) {
})

In the above example, result.rows will contain rows 13 through 24, while result.count will return the total number of rows that matched your query.

See:

Params:

Name Type Description
[findOptions] Object See findAll
[queryOptions] Object See Sequelize.query

Aliases: findAndCountAll


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

View code
Find the maximum value of field

See:

Params:

Name Type Description
field String
[options] Object See aggregate

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

View code
Find the minimum value of field

See:

Params:

Name Type Description
field String
[options] Object See aggregate

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

View code
Find the sum of field

See:

Params:

Name Type Description
field String
[options] Object See 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:

Name Type Description
values Object
[options] Object
[options.raw=false] Boolean If set to true, values will ignore field and virtual setters.
[options.isNewRecord=true] Boolean
[options.isDirty=true] Boolean
[options.include] Array an 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:

Name Type Description
values Object
[options] Object
[options.raw=false] Boolean If set to true, values will ignore field and virtual setters.
[options.isNewRecord=true] Boolean
[options.isDirty=true] Boolean
[options.fields] Array If set, only columns matching those in fields will be saved
[options.include] Array an array of include options - Used to build prefetched/included model instances
[options.onDuplicate] String
[options.transaction] Transaction

findOrInitialize -> Promise<Instance>

View code
Find a row that matches the query, or build (but don't save) the row if none is found.
The successfull result of the promise will be (instance, initialized) - Make sure to use .spread()

Params:

Name Type Description
options Object
options.where Object A hash of search attributes.
[options.defaults] Object Default values to use if building a new instance
[options.transaction] Object Transaction to run query under

Aliases: findOrBuild


findOrCreate(options, [queryOptions]) -> Promise<Instance|created>

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

If no transaction is passed in the queryOptions object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call.
However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has comitted. In this case, an instance of sequelize.TimeoutError will be thrown instead.
If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.

Params:

Name Type Description
options Object
options.where Object where A hash of search attributes.
[options.defaults] Object Default values to use if creating a new instance
[queryOptions] Object Options passed to the find and create calls

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

Note 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:

Name Type Description
values Object
[options] Object
[options.fields=Object.keys(this.attributes)] Array The fields to insert / update. Defaults to all fields

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

Params:

Name Type Description
records Array List of objects (key/value pairs) to create instances from
[options] Object
[options.fields] Array Fields to insert (defaults to all fields)
[options.validate=false] Boolean Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
[options.hooks=true] Boolean Run before / after bulk create hooks?
[options.individualHooks=false] Boolean Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
[options.ignoreDuplicates=false] Boolean Ignore duplicate values for primary keys? (not supported by postgres)
[options.updateOnDuplicate] Array Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.

destroy(options) -> Promise<undefined>

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

Params:

Name Type Description
options Object
[options.where] Object Filter the destroy
[options.hooks=true] Boolean Run before / after bulk destroy hooks?
[options.individualHooks=false] Boolean If set to true, destroy will find all records within the where parameter and will execute before / after bulkDestroy hooks on each row
[options.limit] Number How many rows to delete
[options.force=false] Boolean Delete instead of setting deletedAt to current timestamp (only applicable if paranoid is enabled)
[options.truncate=false] 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=false] Boolean Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
[options.transaction] Transaction

restore(options) -> Promise<undefined>

View code
Restore multiple instances if paranoid is enabled.

Params:

Name Type Description
options Object
[options.where] Object Filter the restore
[options.hooks=true] Boolean Run before / after bulk restore hooks?
[options.individualHooks=false] 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
[options.transaction] Transaction

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 number
of affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true.)

Params:

Name Type Description
values Object
options Object
options.where Object Options to describe the scope of the search.
[options.validate=true] Boolean Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
[options.hooks=true] Boolean Run before / after bulk update hooks?
[options.individualHooks=false] Boolean Run before / after update hooks?
[options.returning=false] Boolean Return the affected rows (only for postgres)
[options.limit] Number How many rows to update (only for mysql and mariadb)
[options.transaction] Transaction

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.


Class Instance

View code
This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not
instantiate the Instance class directly, instead you access it using the finder and creation methods on the model.

Instance 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:


isNewRecord -> Boolean

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


Model() -> Model

View code
Returns the Model the instance was created from.

See:


sequelize() -> Sequelize

View code
A reference to the sequelize instance

See:


isDeleted() -> Boolean

View code
If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. Otherwise, always returns false.


values() -> Object

View code
Get the values of this Instance. Proxies to this.get

See:


isDirty() -> Boolean

View code
A getter for this.changed(). Returns true if any keys have changed.

See:


primaryKeyValues() -> Object

View code
Get the values of the primary keys of this instance.


getDataValue(key) -> any

View code
Get the value of the underlying data value

Params:

Name Type Description
key String

setDataValue(key, value)

View code
Update the underlying data value

Params:

Name Type Description
key String
value any

get([key], [options]) -> Object|any

View code
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 Description
[key] String
[options] Object
[options.plain=false] Boolean If set to true, included instances will be returned as plain objects

set(key, value, [options])

View code
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, so that you can later see which fields changed (see changed).

Set can also be used to build instances for associations, if you have values for those. TODO - mick should probably write something here about how includes in set works - perhaps also even some tests?

See:

Params:

Name Type Description
key String | Object
value any
[options] Object
[options.raw=false] Boolean If set to true, field and virtual setters will be ignored
[options.reset=false] Boolean Clear all previously set data values
[options.include] Object

Aliases: setAttributes


changed([key]) -> Boolean|Array

View code
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.

Params:

Name Type Description
[key] String

previous(key) -> any

View code
Returns the previous value for key from _previousDataValues.

Params:

Name Type Description
key String

save([options]) -> Promise<this|Errors.ValidationError>

View code
Validate this instance, and if the validation passes, persist it to the database.

On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of Sequelize.ValidationError.
This error will have a property for each of the fields for which validation failed, with the error message for that field.

Params:

Name Type Description
[options] Object
[options.fields] Object An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
[options.silent=false] Boolean If true, the updatedAt timestamp will not be updated.
[options.validate=true] Boolean If false, validations won't be run.
[options.transaction] Transaction

reload([options]) -> Promise<this>

View code
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:

Params:

Name Type Description
[options] Object Options that are passed on to Model.find

validate([options]) -> Promise<undefined|Errors.ValidationError>

View code
Validate the attribute of this instance according to validation rules set in the model definition.

Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.

See:

Params:

Name Type 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

updateAttributes(updates, options) -> Promise<this>

View code
This is the same as calling setAttributes, then calling save.

See:

Params:

Name Type Description
updates Object See setAttributes
options Object See save

destroy([options={}]) -> Promise<undefined>

View code
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 Description
[options={}] Object
[options.force=false] Boolean If set to true, paranoid models will actually be deleted
[options.transaction] Transaction

restore([options={}]) -> Promise<undefined>

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

Params:

Name Type Description
[options={}] Object
[options.transaction] Transaction

increment(fields, [options]) -> Promise

View code
Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a

SET column = column + X

query. To get the correct value after an increment into the Instance you should do a reload.

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

See:

Params:

Name Type Description
fields String | Array Object
[options] Object
[options.by=1] Integer The number to increment by
[options.transaction=null] Transaction

decrement(fields, [options]) -> Promise

View code
Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a

SET column = column - X

query. To get the correct value after an decrement into the Instance you should do a reload.

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

See:

Params:

Name Type Description
fields String | Array Object
[options] Object
[options.by=1] Integer The number to decrement by
[options.transaction=null] Transaction

equals(other) -> Boolean

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

Params:

Name Type Description
other Instance

equalsOneOf(others) -> Boolean

View code
Check if this is eqaul to one of others by calling equals

Params:

Name Type Description
others Array

toJSON() -> object

View code
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:


Mixin Mixin

View code
Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions
on a model (the source), and prodiving another model as the first argument to the function (the target).

  • hasOne - adds a foreign key to target
  • belongsTo - add a foreign key to source
  • hasMany - adds a foreign key to target, unless you also specifiy that target hasMany source, in which case a junction table is created with sourceId and targetId

Creating an association will add a foreign key constraint to the attributes. All associations use CASCADE on update and SET NULL on delete, except for n:m, which also uses CASCADE on delete.

When creating associations, you can provide an alias, via the as option. This is usefull if the same model
is associated twice, or you want your association to be called something other than the name of the target model.
As an example, consider the case where users have many pictures, one of which is their profile picture. All pictures
have a userId, but in addition the user model also has a profilePictureId, to be able to easily load the user's profile
picture.

User.hasMany(Picture)
User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false })
user.getPictures() // gets you all pictures
user.getProfilePicture() // gets you only the profile picture
User.findAll({
  where: ...,
  include: [
    { model: Picture }, // load all pictures
    { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be the exact same as the one in the association
  ]
})

To get full control over the foreign key column added by sequelize, you can use the foreignKey option. It can either be a string, that specifies the name, or and object type definition,
equivalent to those passed to sequelize.define.

User.hasMany(Picture, { foreignKey: 'uid' })

The foreign key column in Picture will now be called uid instead of the default userId.

User.hasMany(Picture, {
  foreignKey: {
    name: 'uid'
    allowNull: false
  }
})

This specifies that the uid column can not be null. In most cases this will already be covered by the foreign key costraints, which sequelize creates automatically,
but can be usefull in case where the foreign keys are disabled, e.g. due to circular references (see constraints: false below).

When fetching associated models, you can limit your query to only load some models. These queries are written in the same way as queries to find/findAll. To only get pictures in JPG, you can do:

user.getPictures({
  where: {
    format: 'jpg'
  }
})

There are several ways to update and add new assoications. Continuing with our example of users and pictures:

user.addPicture(p) // Add a single picture
user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be deleted
user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current associations

You don't have to pass in a complete object to the association functions, if your associated model has a single primary key:

user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture

In the example above we have specified that a user belongs to his profile picture. Conceptually, this might not make sense,
but since we want to add the foreign key to the user model this is the way to do it.
Note how we also specified constraints: false for profile picture. This is because we add a foreign key from
user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys to both, it would
create a cyclic dependency, and sequelize would not know which table to create first, since user depends on picture, and picture
depends on user. These kinds of problems are detected by sequelize before the models are synced to the database, and you will
get an error along the lines of Error: Cyclic dependency found. 'users' is dependent of itself. If you encounter this,
you should either disable some constraints, or rethink your associations completely.


hasOne(target, [options])

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

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

The following methods are injected on the source:

  • get[AS] - for example getProfile(finder). The finder object is passed to target.find.
  • set[AS] - for example setProfile(instance, options). Options are passed to target.save
  • create[AS] - for example createProfile(value, options). Builds and saves a new instance of the associated model. Values and options are passed on to target.create

All methods return a promise

Params:

Name Type Description
target Model
[options] object
[options.hooks=false] boolean Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
[options.as] string The alias of this model, in singular form. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the singularized name of target
[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 Sequelize.define for syntax). When using an object, you can add a name property to set the name of the colum. Defaults to the name of source + primary key of source
[options.onDelete='SET NULL'] string
[options.onUpdate='CASCADE'] string
[options.constraints=true] boolean Should on update and on delete constraints be enabled on the foreign key.

belongsTo(target, [options])

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

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

The following methods are injected on the source:

  • get[AS] - for example getUser(finder). The finder object is passed to target.find.
  • set[AS] - for example setUser(instance, options). Options are passed to this.save
  • create[AS] - for example createUser(value, options). Builds and saves a new instance of the associated model. Values and options are passed on to target.create

All methods return a promise

Params:

Name Type Description
target Model
[options] object
[options.hooks=false] boolean Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
[options.as] string The alias of this model, in singular form. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the singularized name of target
[options.foreignKey] string | object The name of the foreign key in the source table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the colum. Defaults to the name of target + primary key of target
[options.onDelete='SET NULL'] string
[options.onUpdate='CASCADE'] string
[options.constraints=true] boolean Should on update and on delete constraints be enabled on the foreign key.

hasMany(target, [options])

View code
Create an association that is either 1:m or n:m.

// Create a 1:m association between user and project
User.hasMany(Project)
// Create a n:m association between user and project
User.hasMany(Project)
Project.hasMany(User)

By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as through in the options.

The following methods are injected on the source:

  • get[AS] - for example getPictures(finder). The finder object is passed to target.find.
  • set[AS] - for example setPictures(instances, defaultAttributes|options). Update the associations. All currently associated models that are not in instances will be removed.
  • add[AS] - for example addPicture(instance, defaultAttributes|options). Add another associated object.
  • add[AS] [plural] - for example addPictures([instance1, instance2], defaultAttributes|options). Add some more associated objects.
  • create[AS] - for example createPicture(values, options). Build and save a new association.
  • remove[AS] - for example removePicture(instance). Remove a single association.
  • remove[AS] [plural] - for example removePictures(instance). Remove multiple association.
  • has[AS] - for example hasPicture(instance). Is source associated to this target?
  • has[AS] [plural] - for example hasPictures(instances). Is source associated to all these targets?

All methods return a promise

If you use a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before
with a join table that stores whether the project has been started yet:

var UserProjects = sequelize.define('userprojects', {
  started: Sequelize.BOOLEAN
})
User.hasMany(Project, { through: UserProjects })
Project.hasMany(User, { through: UserProjects })
jan.addProject(homework, { started: false }) // The homework project is not started yet
jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started

If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:

p1.userprojects {
  started: true
}
user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.

Similarily, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.

user.getProjects().success(function (projects) {
  var p1 = projects[0]
  p1.userprojects.started // Is this project started yet?
})

Params:

Name Type Description
target Model
[options] object
[options.hooks=false] boolean Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
[options.through] Model | string object
[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=true] 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.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 plural and singular keys. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the pluralized name of target
[options.foreignKey] string | object The name of the foreign key in the target table / join table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the colum. Defaults to the name of source + primary key of source
[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='SET NULL CASCADE'] string
[options.onUpdate='CASCADE'] string
[options.constraints=true] boolean Should on update and on delete constraints be enabled on the foreign key.

belongsToMany(target, [options])

View code
Create an N:M association with a join table

User.belongsToMany(Project)
Project.belongsToMany(User)

By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as through in the options.

The following methods are injected on the source:

  • get[AS] - for example getPictures(finder). The finder object is passed to target.find.
  • set[AS] - for example setPictures(instances, defaultAttributes|options). Update the associations. All currently associated models that are not in instances will be removed.
  • add[AS] - for example addPicture(instance, defaultAttributes|options). Add another associated object.
  • add[AS] [plural] - for example addPictures([instance1, instance2], defaultAttributes|options). Add some more associated objects.
  • create[AS] - for example createPicture(values, options). Build and save a new association.
  • remove[AS] - for example removePicture(instance). Remove a single association.
  • remove[AS] [plural] - for example removePictures(instance). Remove multiple association.
  • has[AS] - for example hasPicture(instance). Is source associated to this target?
  • has[AS] [plural] - for example hasPictures(instances). Is source associated to all these targets?

All methods return a promise

If you use a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before
with a join table that stores whether the project has been started yet:

var UserProjects = sequelize.define('userprojects', {
  started: Sequelize.BOOLEAN
})
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
jan.addProject(homework, { started: false }) // The homework project is not started yet
jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started

If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:

p1.userprojects {
  started: true
}
user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.

Similarily, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.

user.getProjects().then(function (projects) {
  var p1 = projects[0]
  p1.userprojects.started // Is this project started yet?
})

Params:

Name Type Description
target Model
[options] object
[options.hooks=false] boolean Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
[options.through] Model | string object
[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=true] 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.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 plural and singular keys. See also the name option passed to sequelize.define. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the pluralized name of target
[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 Sequelize.define for syntax). When using an object, you can add a name property to set the name of the colum. Defaults to the name of source + primary key of source
[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 Sequelize.define for syntax). When using an object, you can add a name property to set the name of the colum. Defaults to the name of target + primary key of target
[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='SET NULL CASCADE'] string
[options.onUpdate='CASCADE'] string
[options.constraints=true] boolean Should on update and on delete constraints be enabled on the foreign key.

Mixin Hooks

View code
Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. Hooks can be added to you models in three ways:

  1. By specifying them as options in sequelize.define
  2. By calling hook() with a string and your hook handler function
  3. By calling the function with the same name as the hook you want
// Method 1
sequelize.define(name, { attributes }, {
  hooks: {
    beforeBulkCreate: function () {
      // can be a single function
    },
    beforeValidate: [
      function () {},
      function() {} // Or an array of several
    ]
  }
})
// Method 2
Model.hook('afterDestroy', function () {})
// Method 3
Model.afterBulkUpdate(function () {})

See:


addHook(hooktype, [name], fn)

View code
Add a hook to the model

Params:

Name Type Description
hooktype String
[name] String Provide a name for the hook function. This serves no purpose, other than the ability to be able to order hooks based on some sort of priority system in the future.
fn Function The hook function

Aliases: hook


beforeValidate(name, fn)

View code
A hook that is run before validation

Params:

Name Type Description
name String
fn Function A callback function that is called with instance, options, callback(err)

afterValidate(name, fn)

View code
A hook that is run after validation

Params:

Name Type Description
name String
fn Function A callback function that is called with instance, options, callback(err)

beforeCreate(name, fn)

View code
A hook that is run before creating a single instance

Params:

Name Type Description
name String
fn Function A callback function that is called with attributes, options, callback(err)

afterCreate(name, fn)

View code
A hook that is run after creating a single instance

Params:

Name Type Description
name String
fn Function A callback function that is called with attributes, options, callback(err)

beforeDestroy(name, fn)

View code
A hook that is run before destroying a single instance

Params:

Name Type Description
name String
fn Function A callback function that is called with instance, options, callback(err)

Aliases: beforeDelete


afterDestroy(name, fn)

View code
A hook that is run after destroying a single instance

Params:

Name Type Description
name String
fn Function A callback function that is called with instance, options, callback(err)

Aliases: afterDelete


beforeUpdate(name, fn)

View code
A hook that is run before updating a single instance

Params:

Name Type Description
name String
fn Function A callback function that is called with instance, options, callback(err)

afterUpdate(name, fn)

View code
A hook that is run after updating a single instance

Params:

Name Type Description
name String
fn Function A callback function that is called with instance, options, callback(err)

beforeBulkCreate(name, fn)

View code
A hook that is run before creating instances in bulk

Params:

Name Type Description
name String
fn Function A callback function that is called with instances, options, callback(err)

afterBulkCreate(name, fn)

View code
A hook that is run after creating instances in bulk

Params:

Name Type Description
name String
fn Function A callback function that is called with instances, options, callback(err)

beforeBulkDestroy(name, fn)

View code
A hook that is run before destroying instances in bulk

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

Aliases: beforeBulkDelete


afterBulkDestroy(name, fn)

View code
A hook that is run after destroying instances in bulk

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

Aliases: afterBulkDelete


beforeBulkUpdate(name, fn)

View code
A hook that is run after updating instances in bulk

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

afterBulkUpdate(name, fn)

View code
A hook that is run after updating instances in bulk

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

beforeFind(name, fn)

View code
A hook that is run before a find (select) query

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

beforeFindAfterExpandIncludeAll(name, fn)

View code
A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

beforeFindAfterOptions(name, fn)

View code
A hook that is run before a find (select) query, after all option parsing is complete

Params:

Name Type Description
name String
fn Function A callback function that is called with options, callback(err)

afterFind(name, fn)

View code
A hook that is run after a find (select) query

Params:

Name Type Description
name String
fn Function A callback function that is called with instance(s), options, callback(err)

beforeDefine(name, fn)

View code
A hook that is run before a define call

Params:

Name Type Description
name String
fn Function A callback function that is called with attributes, options, callback(err)

afterDefine(name, fn)

View code
A hook that is run after a define call

Params:

Name Type Description
name String
fn Function A callback function that is called with factory, callback(err)

beforeInit(name, fn)

View code
A hook that is run before Sequelize() call

Params:

Name Type Description
name String
fn Function A callback function that is called with config, options, callback(err)

afterInit(name, fn)

View code
A hook that is run after Sequelize() call

Params:

Name Type Description
name String
fn Function A callback function that is called with sequelize, callback(err)

Class Promise

View code
A slightly modified version of bluebird promises. This means that, on top of the methods below, you can also call all the methods listed on the link below.

The main difference is that sequelize promises allows you to attach a listener that will be called with the generated SQL, each time a query is run.

The sequelize promise class works seamlessly with other A+/thenable libraries, with one exception.
If you want to propagate SQL events across then, all calls etc., you must use sequelize promises exclusively.

Mixes:


on(evt, fct)

View code
Listen for events, event emitter style. Mostly for backwards compat. with EventEmitter

Deprecated

Params:

Name Type Description
evt String
fct Function

emit(type, value(s)*)

View code
Emit an event from the emitter
Deprecated

Params:

Name Type Description
type string The type of event
value(s)* any All other arguments will be passed to the event listeners

success(onSuccess) -> this

View code
Listen for success events.

promise.success(function (result) {
 //...
});

Deprecated

Params:

Name Type Description
onSuccess function

Aliases: ok


error(onError) -> this

View code
Listen for error events

promise.error(function (err) {
 //...
});

Deprecated

Params:

Name Type Description
onError function

Aliases: fail, failure


done(onDone) -> this

View code
Listen for both success and error events.

promise.done(function (err, result) {
 //...
});

Deprecated done(fct) is deprecated, done() is regular promise syntax to explicitly signal the end of a promise chain and will not be deprecated

Params:

Name Type Description
onDone function

Aliases: complete


sql(onSQL) -> this

View code
Attach a function that is called every time the function that created this emitter executes a query.

Params:

Name Type Description
onSQL function

proxy(promise, [options]) -> this

View code
Proxy every event of this promise to another one.

Deprecated

Params:

Name Type Description
promise SequelizePromise The promise that should receive the events.
[options] Object
[options.events] Array An array of the events to proxy. Defaults to sql, error and success

Class Transaction

View code
The transaction object is used to identify a running transaction. It is created by calling Sequelize.transaction().

To run a query under a transaction, you should pass the transaction in the options object.


ISOLATION_LEVELS

View code
The possible isolations levels to use when starting a transaction

{
  READ_UNCOMMITTED: "READ UNCOMMITTED",
  READ_COMMITTED: "READ COMMITTED",
  REPEATABLE_READ: "REPEATABLE READ",
  SERIALIZABLE: "SERIALIZABLE"
}

LOCK

View code
Possible options for row locking. Used in conjuction with find calls:

t1 // is a transaction
Model.findAll({
  where: ...
}, {
  transaction: t1,
  lock: t1.LOCK.UPDATE,
  lock: t1.LOCK.SHARE
})

commit() -> this

View code
Commit the transaction


rollback() -> this

View code
Rollback (abort) the transaction


Class DataTypes

View code
A convenience class holding commonly used data types. The datatypes are used when definining a new model using Sequelize.define, like this:

sequelize.define('model', {
  column: DataTypes.INTEGER
})

When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using DataTypes.BLOB, mean
that that column will be returned as an instance of Buffer when being fetched by sequelize.

Some data types have special properties that can be accessed in order to change the data type. For example, to get an unsigned integer with zerofill you can do DataTypes.INTEGER.UNSIGNED.ZEROFILL.
The order you access the properties in do not matter, so DataTypes.INTEGER.ZEROFILL.UNSIGNED is fine as well. The available properties are listed under each data type.

To provide a length for the data type, you can invoke it like a function: INTEGER(2)

Three of the values provided here (NOW, UUIDV1 and UUIDV4) are special default values, that should not be used to define types. Instead they are used as shorthands for
defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:

sequelize.define('model', {
  uuid: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV1,
    primaryKey: true
  }
})

STRING

View code
A variable length string. Default length 255

Available properties: BINARY


CHAR

View code
A fixed length string. Default length 255

Available properties: BINARY


TEXT

View code
An unlimited length text column


INTEGER

View code
A 32 bit integer.

Available properties: UNSIGNED, ZEROFILL


BIGINT

View code
A 64 bit integer.

Available properties: UNSIGNED, ZEROFILL


DATE

View code
A datetime column


DATEONLY

View code
A date only column


BOOLEAN

View code
A boolean / tinyint column, depending on dialect


FLOAT

View code
Floating point number. Accepts one or two arguments for precision

Available properties: UNSIGNED, ZEROFILL


NOW

View code
A default value of the current timestamp


BLOB

View code
Binary storage. Available lengths: tiny, medium, long


DECIMAL

View code
Decimal number. Accepts one or two arguments for precision

Available properties: UNSIGNED, ZEROFILL


UUID

View code
A column storing a unique univeral identifier. Use with UUIDV1 or UUIDV4 for default values.


UUIDV1

View code
A default unique universal identifier generated following the UUID v1 standard


UUIDV4

View code
A default unique universal identifier generated following the UUID v2 standard


HSTORE

View code
A key / value column. Only available in postgres.


VIRTUAL

View code
A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model
that is returned to the user but not stored in the DB.

You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:

sequelize.define('user', {
  password_hash: DataTypes.STRING
  password: {
    type: DataTypes.VIRTUAL,
    set: function (val) {
       this.setDataValue('password', val);
       this.setDataValue('password_hash', this.salt + val);
     },
     validate: {
        isLongEnough: function (val) {
          if (val.length < 7) {
            throw new Error("Please choose a longer password")
         }
      }
    }
  }
})

In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
Aliases: NONE


ENUM

View code
An enumeration. DataTypes.ENUM('value', 'another value').


ARRAY()

View code
An array of type, e.g. DataTypes.ARRAY(DataTypes.DECIMAL). Only available in postgres.


Class Errors

View code
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor.
All sequelize errors inherit from the base JS error object.


new BaseError()

View code
The Base Error all Sequelize Errors inherit from.

Aliases: Error


new ValidationError(message, [errors])

View code
Validation Error. Thrown when the sequelize validation has failed. The error contains an errors property,
which is an array with 1 or more ValidationErrorItems, one for each validation that failed.

Params:

Name Type Description
message string Error message
[errors] Array Array of ValidationErrorItem objects describing the validation errors

Extends: BaseError


get(path)

View code
Gets all validation error items for the path / field specified.

Params:

Name Type Description
path string The path to be checked for error items

errors()

View code
An array of ValidationErrorItems


new DatabaseError()

View code
A base class for all database related errors.

Extends: BaseError


parent()

View code
The database specific error which triggered this one


sql()

View code
The SQL that triggered the error


new TimeoutError()

View code
Thrown when a database query times out because of a deadlock

Extends: DatabaseError


new UniqueConstraintError()

View code
Thrown when a unique constraint is violated in the database

Extends: DatabaseError


new ForeignKeyConstraintError()

View code
Thrown when a foreign key constraint is violated in the database

Extends: DatabaseError


message()

View code
The message from the DB.


fields()

View code
The fields of the unique constraint


value()

View code
The value(s) which triggered the error


index()

View code
The name of the index that triggered the error


new ValidationErrorItem(message, type, path, value)

View code
Validation Error Item
Instances of this class are included in the ValidationError.errors property.

Params:

Name Type Description
message string An error message
type string The type of the validation error
path string The field that triggered the validation error
value string The value that generated the error

new ConnectionError()

View code
A base class for all connection related errors.

Extends: BaseError


parent()

View code
The connection specific error which triggered this one


new ConnectionRefusedError()

View code
Thrown when a connection to a database is refused

Extends: ConnectionError


new AccessDeniedError()

View code
Thrown when a connection to a database is refused due to insufficient privileges

Extends: ConnectionError


new HostNotFoundError()

View code
Thrown when a connection to a database has a hostname that was not found

Extends: ConnectionError


new HostNotReachableError()

View code
Thrown when a connection to a database has a hostname that was not reachable

Extends: ConnectionError


new InvalidConnectionError()

View code
Thrown when a connection to a database has invalid values for any of the connection parameters

Extends: ConnectionError


new ConnectionTimedOutError()

View code
Thrown when a connection to a database times out

Extends: ConnectionError