Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.
Sequelize follows SEMVER. Supports Node v6 and above to use ES6 features.
Sequelize v5 was released on March 13, 2019. Official TypeScript typings are now included.
You are currently looking at the Tutorials and Guides for Sequelize. You might also be interested in the API Reference.
Quick example
const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
class User extends Model {}
User.init({
username: DataTypes.STRING,
birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });
sequelize.sync()
.then(() => User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20)
}))
.then(jane => {
console.log(jane.toJSON());
});
To learn more about how to use Sequelize, read the tutorials available in the left menu. Begin with Getting Started.
Getting started
In this tutorial you will learn to make a simple setup of Sequelize to learn the basics.
Installing
Sequelize is available via npm (or yarn).
npm install --save sequelize
You'll also have to manually install the driver for your database of choice:
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
Setting up a connection
To connect to the database, you must create a Sequelize instance. This can be done by either passing the connection parameters separately to the Sequelize constructor or by passing a single connection URI:
const Sequelize = require('sequelize');
// Option 1: Passing parameters separately
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});
// Option 2: Passing a connection URI
const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname');
The Sequelize constructor takes a whole slew of options that are documented in the API Reference for the Sequelize constructor.
Note: setting up SQLite
If you're using SQLite, you should use the following instead:
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'path/to/database.sqlite'
});
Note: connection pool (production)
If you're connecting to the database from a single process, you should create only one Sequelize instance. Sequelize will set up a connection pool on initialization. This connection pool can be configured through the constructor's options
parameter (using options.pool
), as is shown in the following example:
const sequelize = new Sequelize(/* ... */, {
// ...
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
Learn more in the API Reference for the Sequelize constructor. If you're connecting to the database from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of such that the total maximum size is respected. For example, if you want a max connection pool size of 90 and you have three processes, the Sequelize instance of each process should have a max connection pool size of 30.
Testing the connection
You can use the .authenticate()
function to test if the connection is OK:
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
Closing the connection
Sequelize will keep the connection open by default, and use the same connection for all queries. If you need to close the connection, call sequelize.close()
(which is asynchronous and returns a Promise).
Modeling a table
A model is a class that extends Sequelize.Model
. Models can be defined in two equivalent ways. The first, with Sequelize.Model.init(attributes, options)
:
const Model = Sequelize.Model;
class User extends Model {}
User.init({
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
}, {
sequelize,
modelName: 'user'
// options
});
Alternatively, using sequelize.define
:
const User = sequelize.define('user', {
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
}, {
// options
});
Internally, sequelize.define
calls Model.init
.
The above code tells Sequelize to expect a table named users
in the database with the fields firstName
and lastName
. The table name is automatically pluralized by default (a library called inflection is used under the hood to do this). This behavior can be stopped for a specific model by using the freezeTableName: true
option, or for all models by using the define
option from the Sequelize constructor.
Sequelize also defines by default the fields id
(primary key), createdAt
and updatedAt
to every model. This behavior can also be changed, of course (check the API Reference to learn more about the available options).
Changing the default model options
The Sequelize constructor takes a define
option which will change the default options for all defined models.
const sequelize = new Sequelize(connectionURI, {
define: {
// The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.
// This was true by default, but now is false by default
timestamps: false
}
});
// Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.
class Foo extends Model {}
Foo.init({ /* ... */ }, { sequelize });
// Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.
class Bar extends Model {}
Bar.init({ /* ... */ }, { sequelize, timestamps: true });
You can read more about creating models in the Model.init API Reference, or in the sequelize.define API reference.
Synchronizing the model with the database
If you want Sequelize to automatically create the table (or modify it as needed) according to your model definition, you can use the sync
method, as follows:
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model definition
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
Synchronizing all models at once
Instead of calling sync()
for every model, you can call sequelize.sync()
which will automatically sync all models.
Note for production
In production, you might want to consider using Migrations instead of calling sync()
in your code. Learn more in the Migrations guide.
Querying
A few simple queries are shown below:
// Find all users
User.findAll().then(users => {
console.log("All users:", JSON.stringify(users, null, 4));
});
// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {
console.log("Jane's auto-generated ID:", jane.id);
});
// Delete everyone named "Jane"
User.destroy({
where: {
firstName: "Jane"
}
}).then(() => {
console.log("Done");
});
// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" }, {
where: {
lastName: null
}
}).then(() => {
console.log("Done");
});
Sequelize has a lot of options for querying. You will learn more about those in the next tutorials. It is also possible to make raw SQL queries, if you really need them.
Promises and async/await
As shown above by the extensive usage of .then
calls, Sequelize uses Promises extensively. This means that, if your Node version supports it, you can use ES2017 async/await
syntax for all asynchronous calls made with Sequelize.
Also, all Sequelize promises are in fact Bluebird promises, so you have the rich Bluebird API to use as well (for example, using finally
, tap
, tapCatch
, map
, mapSeries
, etc). You can access the Bluebird constructor used internally by Sequelize with Sequelize.Promise
, if you want to set any Bluebird specific options.
Dialects
Sequelize is independent from specific dialects. This means that you'll have to install the respective connector library to your project yourself.
MySQL
In order to get Sequelize working nicely together with MySQL, you'll need to installmysql2@^1.5.2
or higher. Once that's done you can use it like this:
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql'
})
Note: You can pass options directly to dialect library by setting the
dialectOptions
parameter.
MariaDB
Library for MariaDB is mariadb
.
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mariadb',
dialectOptions: {connectTimeout: 1000} // mariadb connector option
})
or using connection String:
const sequelize = new Sequelize('mariadb://user:[email protected]:9821/database')
SQLite
For SQLite compatibility you'll needsqlite3@^4.0.0
. Configure Sequelize like this:
const sequelize = new Sequelize('database', 'username', 'password', {
// sqlite! now!
dialect: 'sqlite',
// the storage engine for sqlite
// - default ':memory:'
storage: 'path/to/database.sqlite'
})
Or you can use a connection string as well with a path:
const sequelize = new Sequelize('sqlite:/home/abs/path/dbname.db')
const sequelize = new Sequelize('sqlite:relativePath/dbname.db')
PostgreSQL
For PostgreSQL, two libraries are needed, pg@^7.0.0
and pg-hstore
. You'll just need to define the dialect:
const sequelize = new Sequelize('database', 'username', 'password', {
// gimme postgres, please!
dialect: 'postgres'
})
To connect over a unix domain socket, specify the path to the socket directory
in the host
option.
The socket path must start with /
.
const sequelize = new Sequelize('database', 'username', 'password', {
// gimme postgres, please!
dialect: 'postgres',
host: '/path/to/socket_directory'
})
MSSQL
The library for MSSQL istedious@^6.0.0
You'll just need to define the dialect.
Please note: tedious@^6.0.0
requires you to nest MSSQL specific options inside an additional options
-object inside the dialectOptions
-object.
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mssql',
dialectOptions: {
options: {
useUTC: false,
dateFirst: 1,
}
}
})
Datatypes
Below are some of the datatypes supported by sequelize. For a full and updated list, see DataTypes.
Sequelize.STRING // VARCHAR(255)
Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT
Sequelize.TEXT('tiny') // TINYTEXT
Sequelize.CITEXT // CITEXT PostgreSQL and SQLite only.
Sequelize.INTEGER // INTEGER
Sequelize.BIGINT // BIGINT
Sequelize.BIGINT(11) // BIGINT(11)
Sequelize.FLOAT // FLOAT
Sequelize.FLOAT(11) // FLOAT(11)
Sequelize.FLOAT(11, 10) // FLOAT(11,10)
Sequelize.REAL // REAL PostgreSQL only.
Sequelize.REAL(11) // REAL(11) PostgreSQL only.
Sequelize.REAL(11, 12) // REAL(11,12) PostgreSQL only.
Sequelize.DOUBLE // DOUBLE
Sequelize.DOUBLE(11) // DOUBLE(11)
Sequelize.DOUBLE(11, 10) // DOUBLE(11,10)
Sequelize.DECIMAL // DECIMAL
Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)
Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
Sequelize.DATE(6) // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision
Sequelize.DATEONLY // DATE without time.
Sequelize.BOOLEAN // TINYINT(1)
Sequelize.ENUM('value 1', 'value 2') // An ENUM with allowed values 'value 1' and 'value 2'
Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only.
Sequelize.ARRAY(Sequelize.ENUM) // Defines an array of ENUM. PostgreSQL only.
Sequelize.JSON // JSON column. PostgreSQL, SQLite and MySQL only.
Sequelize.JSONB // JSONB column. PostgreSQL only.
Sequelize.BLOB // BLOB (bytea for PostgreSQL)
Sequelize.BLOB('tiny') // TINYBLOB (bytea for PostgreSQL. Other options are medium and long)
Sequelize.UUID // UUID datatype for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (use defaultValue: Sequelize.UUIDV1 or Sequelize.UUIDV4 to make sequelize generate the ids automatically)
Sequelize.CIDR // CIDR datatype for PostgreSQL
Sequelize.INET // INET datatype for PostgreSQL
Sequelize.MACADDR // MACADDR datatype for PostgreSQL
Sequelize.RANGE(Sequelize.INTEGER) // Defines int4range range. PostgreSQL only.
Sequelize.RANGE(Sequelize.BIGINT) // Defined int8range range. PostgreSQL only.
Sequelize.RANGE(Sequelize.DATE) // Defines tstzrange range. PostgreSQL only.
Sequelize.RANGE(Sequelize.DATEONLY) // Defines daterange range. PostgreSQL only.
Sequelize.RANGE(Sequelize.DECIMAL) // Defines numrange range. PostgreSQL only.
Sequelize.ARRAY(Sequelize.RANGE(Sequelize.DATE)) // Defines array of tstzrange ranges. PostgreSQL only.
Sequelize.GEOMETRY // Spatial column. PostgreSQL (with PostGIS) or MySQL only.
Sequelize.GEOMETRY('POINT') // Spatial column with geometry type. PostgreSQL (with PostGIS) or MySQL only.
Sequelize.GEOMETRY('POINT', 4326) // Spatial column with geometry type and SRID. PostgreSQL (with PostGIS) or MySQL only.
The BLOB datatype allows you to insert data both as strings and as buffers. When you do a find or findAll on a model which has a BLOB column, that data will always be returned as a buffer.
If you are working with the PostgreSQL TIMESTAMP WITHOUT TIME ZONE and you need to parse it to a different timezone, please use the pg library's own parser:
require('pg').types.setTypeParser(1114, stringValue => {
return new Date(stringValue + '+0000');
// e.g., UTC offset. Use any offset that you would like.
});
In addition to the type mentioned above, integer, bigint, float and double also support unsigned and zerofill properties, which can be combined in any order: Be aware that this does not apply for PostgreSQL!
Sequelize.INTEGER.UNSIGNED // INTEGER UNSIGNED
Sequelize.INTEGER(11).UNSIGNED // INTEGER(11) UNSIGNED
Sequelize.INTEGER(11).ZEROFILL // INTEGER(11) ZEROFILL
Sequelize.INTEGER(11).ZEROFILL.UNSIGNED // INTEGER(11) UNSIGNED ZEROFILL
Sequelize.INTEGER(11).UNSIGNED.ZEROFILL // INTEGER(11) UNSIGNED ZEROFILL
The examples above only show integer, but the same can be done with bigint and float
Usage in object notation:
// for enums:
class MyModel extends Model {}
MyModel.init({
states: {
type: Sequelize.ENUM,
values: ['active', 'pending', 'deleted']
}
}, { sequelize })
Array(ENUM)
Its only supported with PostgreSQL.
Array(Enum) type require special treatment. Whenever Sequelize will talk to database it has to typecast Array values with ENUM name.
So this enum name must follow this pattern enum_<table_name>_<col_name>
. If you are using sync
then correct name will automatically be generated.
Range types
Since range types have extra information for their bound inclusion/exclusion it's not very straightforward to just use a tuple to represent them in javascript.
When supplying ranges as values you can choose from the following APIs:
// defaults to '["2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")'
// inclusive lower bound, exclusive upper bound
Timeline.create({ range: [new Date(Date.UTC(2016, 0, 1)), new Date(Date.UTC(2016, 1, 1))] });
// control inclusion
const range = [
{ value: new Date(Date.UTC(2016, 0, 1)), inclusive: false },
{ value: new Date(Date.UTC(2016, 1, 1)), inclusive: true },
];
// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]'
// composite form
const range = [
{ value: new Date(Date.UTC(2016, 0, 1)), inclusive: false },
new Date(Date.UTC(2016, 1, 1)),
];
// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")'
Timeline.create({ range });
However, please note that whenever you get back a value that is range you will receive:
// stored value: ("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]
range // [{ value: Date, inclusive: false }, { value: Date, inclusive: true }]
You will need to call reload after updating an instance with a range type or use returning: true
option.
Special Cases
// empty range:
Timeline.create({ range: [] }); // range = 'empty'
// Unbounded range:
Timeline.create({ range: [null, null] }); // range = '[,)'
// range = '[,"2016-01-01 00:00:00+00:00")'
Timeline.create({ range: [null, new Date(Date.UTC(2016, 0, 1))] });
// Infinite range:
// range = '[-infinity,"2016-01-01 00:00:00+00:00")'
Timeline.create({ range: [-Infinity, new Date(Date.UTC(2016, 0, 1))] });
Extending datatypes
Most likely the type you are trying to implement is already included in DataTypes. If a new datatype is not included, this manual will show how to write it yourself.
Sequelize doesn't create new datatypes in the database. This tutorial explains how to make Sequelize recognize new datatypes and assumes that those new datatypes are already created in the database.
To extend Sequelize datatypes, do it before any instance is created. This example creates a dummy NEWTYPE
that replicates the built-in datatype Sequelize.INTEGER(11).ZEROFILL.UNSIGNED
.
// myproject/lib/sequelize.js
const Sequelize = require('Sequelize');
const sequelizeConfig = require('../config/sequelize')
const sequelizeAdditions = require('./sequelize-additions')
// Function that adds new datatypes
sequelizeAdditions(Sequelize)
// In this exmaple a Sequelize instance is created and exported
const sequelize = new Sequelize(sequelizeConfig)
module.exports = sequelize
// myproject/lib/sequelize-additions.js
module.exports = function sequelizeAdditions(Sequelize) {
DataTypes = Sequelize.DataTypes
/*
* Create new types
*/
class NEWTYPE extends DataTypes.ABSTRACT {
// Mandatory, complete definition of the new type in the database
toSql() {
return 'INTEGER(11) UNSIGNED ZEROFILL'
}
// Optional, validator function
validate(value, options) {
return (typeof value === 'number') && (! Number.isNaN(value))
}
// Optional, sanitizer
_sanitize(value) {
// Force all numbers to be positive
if (value < 0) {
value = 0
}
return Math.round(value)
}
// Optional, value stringifier before sending to database
_stringify(value) {
return value.toString()
}
// Optional, parser for values received from the database
static parse(value) {
return Number.parseInt(value)
}
}
DataTypes.NEWTYPE = NEWTYPE;
// Mandatory, set key
DataTypes.NEWTYPE.prototype.key = DataTypes.NEWTYPE.key = 'NEWTYPE'
// Optional, disable escaping after stringifier. Not recommended.
// Warning: disables Sequelize protection against SQL injections
// DataTypes.NEWTYPE.escape = false
// For convenience
// `classToInvokable` allows you to use the datatype without `new`
Sequelize.NEWTYPE = Sequelize.Utils.classToInvokable(DataTypes.NEWTYPE)
}
After creating this new datatype, you need to map this datatype in each database dialect and make some adjustments.
PostgreSQL
Let's say the name of the new datatype is pg_new_type
in the postgres database. That name has to be mapped to DataTypes.NEWTYPE
. Additionally, it is required to create a child postgres-specific datatype.
// myproject/lib/sequelize-additions.js
module.exports = function sequelizeAdditions(Sequelize) {
DataTypes = Sequelize.DataTypes
/*
* Create new types
*/
...
/*
* Map new types
*/
// Mandatory, map postgres datatype name
DataTypes.NEWTYPE.types.postgres = ['pg_new_type']
// Mandatory, create a postgres-specific child datatype with its own parse
// method. The parser will be dynamically mapped to the OID of pg_new_type.
PgTypes = DataTypes.postgres
PgTypes.NEWTYPE = function NEWTYPE() {
if (!(this instanceof PgTypes.NEWTYPE)) return new PgTypes.NEWTYPE();
DataTypes.NEWTYPE.apply(this, arguments);
}
inherits(PgTypes.NEWTYPE, DataTypes.NEWTYPE);
// Mandatory, create, override or reassign a postgres-specific parser
//PgTypes.NEWTYPE.parse = value => value;
PgTypes.NEWTYPE.parse = DataTypes.NEWTYPE.parse;
// Optional, add or override methods of the postgres-specific datatype
// like toSql, escape, validate, _stringify, _sanitize...
}
Ranges
After a new range type has been defined in postgres, it is trivial to add it to Sequelize.
In this example the name of the postgres range type is newtype_range
and the name of the underlying postgres datatype is pg_new_type
. The key of subtypes
and castTypes
is the key of the Sequelize datatype DataTypes.NEWTYPE.key
, in lower case.
// myproject/lib/sequelize-additions.js
module.exports = function sequelizeAdditions(Sequelize) {
DataTypes = Sequelize.DataTypes
/*
* Create new types
*/
...
/*
* Map new types
*/
...
/*
* Add suport for ranges
*/
// Add postgresql range, newtype comes from DataType.NEWTYPE.key in lower case
DataTypes.RANGE.types.postgres.subtypes.newtype = 'newtype_range';
DataTypes.RANGE.types.postgres.castTypes.newtype = 'pg_new_type';
}
The new range can be used in model definitions as Sequelize.RANGE(Sequelize.NEWTYPE)
or DataTypes.RANGE(DataTypes.NEWTYPE)
.
Model definition
To define mappings between a model and a table, use the define
method. Each column must have a datatype, see more about datatypes.
class Project extends Model {}
Project.init({
title: Sequelize.STRING,
description: Sequelize.TEXT
}, { sequelize, modelName: 'project' });
class Task extends Model {}
Task.init({
title: Sequelize.STRING,
description: Sequelize.TEXT,
deadline: Sequelize.DATE
}, { sequelize, modelName: 'task' })
Apart from datatypes, there are plenty of options that you can set on each column.
class Foo extends Model {}
Foo.init({
// instantiating will automatically set the flag to true if not set
flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true },
// default values for dates => current time
myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },
// setting allowNull to false will add NOT NULL to the column, which means an error will be
// thrown from the DB when the query is executed if the column is null. If you want to check that a value
// is not null before querying the DB, look at the validations section below.
title: { type: Sequelize.STRING, allowNull: false },
// Creating two objects with the same value will throw an error. The unique property can be either a
// boolean, or a string. If you provide the same string for multiple columns, they will form a
// composite unique key.
uniqueOne: { type: Sequelize.STRING, unique: 'compositeIndex' },
uniqueTwo: { type: Sequelize.INTEGER, unique: 'compositeIndex' },
// The unique property is simply a shorthand to create a unique constraint.
someUnique: { type: Sequelize.STRING, unique: true },
// It's exactly the same as creating the index in the model's options.
{ someUnique: { type: Sequelize.STRING } },
{ indexes: [ { unique: true, fields: [ 'someUnique' ] } ] },
// Go on reading for further information about primary keys
identifier: { type: Sequelize.STRING, primaryKey: true },
// autoIncrement can be used to create auto_incrementing integer columns
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },
// You can specify a custom column name via the 'field' attribute:
fieldWithUnderscores: { type: Sequelize.STRING, field: 'field_with_underscores' },
// It is possible to create foreign keys:
bar_id: {
type: Sequelize.INTEGER,
references: {
// This is a reference to another model
model: Bar,
// This is the column name of the referenced model
key: 'id',
// This declares when to check the foreign key constraint. PostgreSQL only.
deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
}
},
// It is possible to add comments on columns for MySQL, PostgreSQL and MSSQL only
commentMe: {
type: Sequelize.INTEGER,
comment: 'This is a column name that has a comment'
}
}, {
sequelize,
modelName: 'foo'
});
The comment option can also be used on a table, see model configuration.
Timestamps
By default, Sequelize will add the attributes createdAt
and updatedAt
to your model so you will be able to know when the database entry went into the db and when it was updated last.
Note that if you are using Sequelize migrations you will need to add the createdAt
and updatedAt
fields to your migration definition:
module.exports = {
up(queryInterface, Sequelize) {
return queryInterface.createTable('my-table', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
// Timestamps
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
})
},
down(queryInterface, Sequelize) {
return queryInterface.dropTable('my-table');
},
}
If you do not want timestamps on your models, only want some timestamps, or you are working with an existing database where the columns are named something else, jump straight on to configuration to see how to do that.
Deferrable
When you specify a foreign key column it is optionally possible to declare the deferrable type in PostgreSQL. The following options are available:
// Defer all foreign key constraint check to the end of a transaction
Sequelize.Deferrable.INITIALLY_DEFERRED
// Immediately check the foreign key constraints
Sequelize.Deferrable.INITIALLY_IMMEDIATE
// Don't defer the checks at all
Sequelize.Deferrable.NOT
The last option is the default in PostgreSQL and won't allow you to dynamically change the rule in a transaction. See the transaction section for further information.
Getters & setters
It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties.
Getters and Setters can be defined in 2 ways (you can mix and match these 2 approaches):
- as part of a single property definition
- as part of a model options
N.B: If a getter or setter is defined in both places then the function found in the relevant property definition will always take precedence.
Defining as part of a property
class Employee extends Model {}
Employee.init({
name: {
type: Sequelize.STRING,
allowNull: false,
get() {
const title = this.getDataValue('title');
// 'this' allows you to access attributes of the instance
return this.getDataValue('name') + ' (' + title + ')';
},
},
title: {
type: Sequelize.STRING,
allowNull: false,
set(val) {
this.setDataValue('title', val.toUpperCase());
}
}
}, { sequelize, modelName: 'employee' });
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(employee => {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
Defining as part of the model options
Below is an example of defining the getters and setters in the model options.
The fullName
getter, is an example of how you can define pseudo properties on your models - attributes which are not actually part of your database schema. In fact, pseudo properties can be defined in two ways: using model getters, or by using a column with the VIRTUAL
datatype. Virtual datatypes can have validations, while getters for virtual attributes cannot.
Note that the this.firstname
and this.lastname
references in the fullName
getter function will trigger a call to the respective getter functions. If you do not want that then use the getDataValue()
method to access the raw value (see below).
class Foo extends Model {
get fullName() {
return this.firstname + ' ' + this.lastname;
}
set fullName(value) {
const names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
}
}
Foo.init({
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
sequelize,
modelName: 'foo'
});
// Or with `sequelize.define`
sequelize.define('Foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
getterMethods: {
fullName() {
return this.firstname + ' ' + this.lastname;
}
},
setterMethods: {
fullName(value) {
const names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
}
}
});
Helper functions for use inside getter and setter definitions
- retrieving an underlying property value - always use
this.getDataValue()
/* a getter for 'title' property */
get() {
return this.getDataValue('title')
}
- setting an underlying property value - always use
this.setDataValue()
/* a setter for 'title' property */
set(title) {
this.setDataValue('title', title.toString().toLowerCase());
}
N.B: It is important to stick to using the setDataValue()
and getDataValue()
functions (as opposed to accessing the underlying "data values" property directly) - doing so protects your custom getters and setters from changes in the underlying model implementations.
Validations
Model validations allow you to specify format/content/inheritance validations for each attribute of the model.
Validations are automatically run on create
, update
and save
. You can also call validate()
to manually validate an instance.
Per-attribute validations
You can define your custom validators or use several built-in validators, implemented by validator.js, as shown below.
class ValidateMe extends Model {}
ValidateMe.init({
bar: {
type: Sequelize.STRING,
validate: {
is: ["^[a-z]+$",'i'], // will only allow letters
is: /^[a-z]+$/i, // same as the previous example using real RegExp
not: ["[a-z]",'i'], // will not allow letters
isEmail: true, // checks for email format ([email protected])
isUrl: true, // checks for url format (http://foo.com)
isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format
isIPv4: true, // checks for IPv4 (129.89.23.1)
isIPv6: true, // checks for IPv6 format
isAlpha: true, // will only allow letters
isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
isNumeric: true, // will only allow numbers
isInt: true, // checks for valid integers
isFloat: true, // checks for valid floating point numbers
isDecimal: true, // checks for any numbers
isLowercase: true, // checks for lowercase
isUppercase: true, // checks for uppercase
notNull: true, // won't allow null
isNull: true, // only allows null
notEmpty: true, // don't allow empty strings
equals: 'specific value', // only allow a specific value
contains: 'foo', // force specific substrings
notIn: [['foo', 'bar']], // check the value is not one of these
isIn: [['foo', 'bar']], // check the value is one of these
notContains: 'bar', // don't allow specific substrings
len: [2,10], // only allow values with length between 2 and 10
isUUID: 4, // only allow uuids
isDate: true, // only allow date strings
isAfter: "2011-11-05", // only allow date strings after a specific date
isBefore: "2011-11-05", // only allow date strings before a specific date
max: 23, // only allow values <= 23
min: 23, // only allow values >= 23
isCreditCard: true, // check for valid credit card numbers
// Examples of custom validators:
isEven(value) {
if (parseInt(value) % 2 !== 0) {
throw new Error('Only even values are allowed!');
}
}
isGreaterThanOtherField(value) {
if (parseInt(value) <= parseInt(this.otherField)) {
throw new Error('Bar must be greater than otherField.');
}
}
}
}
}, { sequelize });
Note that where multiple arguments need to be passed to the built-in validation functions, the arguments to be passed must be in an array. But if a single array argument is to be passed, for instance an array of acceptable strings for isIn
, this will be interpreted as multiple string arguments instead of one array argument. To work around this pass a single-length array of arguments, such as [['one', 'two']]
as shown above.
To use a custom error message instead of that provided by validator.js, use an object instead of the plain value or array of arguments, for example a validator which needs no argument can be given a custom message with
isInt: {
msg: "Must be an integer number of pennies"
}
or if arguments need to also be passed add an args
property:
isIn: {
args: [['en', 'zh']],
msg: "Must be English or Chinese"
}
When using custom validator functions the error message will be whatever message the thrown Error
object holds.
See the validator.js project for more details on the built in validation methods.
Hint: You can also define a custom function for the logging part. Just pass a function. The first parameter will be the string that is logged.
Per-attribute validators and allowNull
If a particular field of a model is set to not allow null (with allowNull: false
) and that value has been set to null
, all validators will be skipped and a ValidationError
will be thrown.
On the other hand, if it is set to allow null (with allowNull: true
) and that value has been set to null
, only the built-in validators will be skipped, while the custom validators will still run.
This means you can, for instance, have a string field which validates its length to be between 5 and 10 characters, but which also allows null
(since the length validator will be skipped automatically when the value is null
):
class User extends Model {}
User.init({
username: {
type: Sequelize.STRING,
allowNull: true,
validate: {
len: [5, 10]
}
}
}, { sequelize });
You also can conditionally allow null
values, with a custom validator, since it won't be skipped:
class User extends Model {}
User.init({
age: Sequelize.INTEGER,
name: {
type: Sequelize.STRING,
allowNull: true,
validate: {
customValidator(value) {
if (value === null && this.age !== 10) {
throw new Error("name can't be null unless age is 10");
}
})
}
}
}, { sequelize });
You can customize allowNull
error message by setting the notNull
validator:
class User extends Model {}
User.init({
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notNull: {
msg: 'Please enter your name'
}
}
}
}, { sequelize });
Model-wide validations
Validations can also be defined to check the model after the field-specific validators. Using this you could, for example, ensure either neither of latitude
and longitude
are set or both, and fail if one but not the other is set.
Model validator methods are called with the model object's context and are deemed to fail if they throw an error, otherwise pass. This is just the same as with custom field-specific validators.
Any error messages collected are put in the validation result object alongside the field validation errors, with keys named after the failed validation method's key in the validate
option object. Even though there can only be one error message for each model validation method at any one time, it is presented as a single string error in an array, to maximize consistency with the field errors.
An example:
class Pub extends Model {}
Pub.init({
name: { type: Sequelize.STRING },
address: { type: Sequelize.STRING },
latitude: {
type: Sequelize.INTEGER,
allowNull: true,
defaultValue: null,
validate: { min: -90, max: 90 }
},
longitude: {
type: Sequelize.INTEGER,
allowNull: true,
defaultValue: null,
validate: { min: -180, max: 180 }
},
}, {
validate: {
bothCoordsOrNone() {
if ((this.latitude === null) !== (this.longitude === null)) {
throw new Error('Require either both latitude and longitude or neither')
}
}
},
sequelize,
})
In this simple case an object fails validation if either latitude or longitude is given, but not both. If we try to build one with an out-of-range latitude and no longitude, raging_bullock_arms.validate()
might return
{
'latitude': ['Invalid number: latitude'],
'bothCoordsOrNone': ['Require either both latitude and longitude or neither']
}
Such validation could have also been done with a custom validator defined on a single attribute (such as the latitude
attribute, by checking (value === null) !== (this.longitude === null)
), but the model-wide validation approach is cleaner.
Configuration
You can also influence the way Sequelize handles your column names:
class Bar extends Model {}
Bar.init({ /* bla */ }, {
// The name of the model. The model will be stored in `sequelize.models` under this name.
// This defaults to class name i.e. Bar in this case. This will control name of auto-generated
// foreignKey and association naming
modelName: 'bar',
// don't add the timestamp attributes (updatedAt, createdAt)
timestamps: false,
// don't delete database entries but set the newly added attribute deletedAt
// to the current date (when deletion was done). paranoid will only work if
// timestamps are enabled
paranoid: true,
// Will automatically set field option for all attributes to snake cased name.
// Does not override attribute with field option already defined
underscored: true,
// disable the modification of table names; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following
freezeTableName: true,
// define the table's name
tableName: 'my_very_custom_table_name',
// Enable optimistic locking. When enabled, sequelize will add a version count attribute
// to the model and throw an OptimisticLockingError error when stale instances are saved.
// Set to true or a string with the attribute name you want to use to enable.
version: true,
// Sequelize instance
sequelize,
})
If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually:
class Foo extends Model {}
Foo.init({ /* bla */ }, {
// don't forget to enable timestamps!
timestamps: true,
// I don't want createdAt
createdAt: false,
// I want updatedAt to actually be called updateTimestamp
updatedAt: 'updateTimestamp',
// And deletedAt to be called destroyTime (remember to enable paranoid for this to work)
deletedAt: 'destroyTime',
paranoid: true,
sequelize,
})
You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
class Person extends Model {}
Person.init({ /* attributes */ }, {
engine: 'MYISAM',
sequelize
})
// or globally
const sequelize = new Sequelize(db, user, pw, {
define: { engine: 'MYISAM' }
})
Finally you can specify a comment for the table in MySQL and PG
class Person extends Model {}
Person.init({ /* attributes */ }, {
comment: "I'm a table comment!",
sequelize
})
Import
You can also store your model definitions in a single file using the import
method. The returned object is exactly the same as defined in the imported file's function. Since v1:5.0
of Sequelize the import is cached, so you won't run into troubles when calling the import of a file twice or more often.
// in your server file - e.g. app.js
const Project = sequelize.import(__dirname + "/path/to/models/project")
// The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above
module.exports = (sequelize, DataTypes) => {
class Project extends sequelize.Model { }
Project.init({
name: DataTypes.STRING,
description: DataTypes.TEXT
}, { sequelize });
return Project;
}
The import
method can also accept a callback as an argument.
sequelize.import('project', (sequelize, DataTypes) => {
class Project extends sequelize.Model {}
Project.init({
name: DataTypes.STRING,
description: DataTypes.TEXT
}, { sequelize })
return Project;
})
This extra capability is useful when, for example, Error: Cannot find module
is thrown even though /path/to/models/project
seems to be correct. Some frameworks, such as Meteor, overload require
, and spit out "surprise" results like :
Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'
This is solved by passing in Meteor's version of require
. So, while this probably fails ...
const AuthorModel = db.import('./path/to/models/project');
... this should succeed ...
const AuthorModel = db.import('project', require('./path/to/models/project'));
Optimistic Locking
Sequelize has built-in support for optimistic locking through a model instance version count.
Optimistic locking is disabled by default and can be enabled by setting the version
property to true in a specific model definition or global model configuration. See model configuration for more details.
Optimistic locking allows concurrent access to model records for edits and prevents conflicts from overwriting data. It does this by checking whether another process has made changes to a record since it was read and throws an OptimisticLockError when a conflict is detected.
Database synchronization
When starting a new project you won't have a database structure and using Sequelize you won't need to. Just specify your model structures and let the library do the rest. Currently supported is the creation and deletion of tables:
// Create the tables:
Project.sync()
Task.sync()
// Force the creation!
Project.sync({force: true}) // this will drop the table first and re-create it afterwards
// drop the tables:
Project.drop()
Task.drop()
// event handling:
Project.[sync|drop]().then(() => {
// ok ... everything is nice!
}).catch(error => {
// oooh, did you enter wrong database credentials?
})
Because synchronizing and dropping all of your tables might be a lot of lines to write, you can also let Sequelize do the work for you:
// Sync all models that aren't already in the database
sequelize.sync()
// Force sync all models
sequelize.sync({force: true})
// Drop all tables
sequelize.drop()
// emit handling:
sequelize.[sync|drop]().then(() => {
// woot woot
}).catch(error => {
// whooops
})
Because .sync({ force: true })
is destructive operation, you can use match
option as an additional safety check.
match
option tells sequelize to 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.
// This will run .sync() only if database name ends with '_test'
sequelize.sync({ force: true, match: /_test$/ });
Expansion of models
Sequelize Models are ES6 classes. You can very easily add custom instance or class level methods.
class User extends Model {
// Adding a class level method
static classLevelMethod() {
return 'foo';
}
// Adding an instance level method
instanceLevelMethod() {
return 'bar';
}
}
User.init({ firstname: Sequelize.STRING }, { sequelize });
Of course you can also access the instance's data and generate virtual getters:
class User extends Model {
getFullname() {
return [this.firstname, this.lastname].join(' ');
}
}
User.init({ firstname: Sequelize.STRING, lastname: Sequelize.STRING }, { sequelize });
// Example:
User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'
Indexes
Sequelize supports adding indexes to the model definition which will be created during Model.sync()
or sequelize.sync
.
class User extends Model {}
User.init({}, {
indexes: [
// Create a unique index on email
{
unique: true,
fields: ['email']
},
// Creates a gin index on data with the jsonb_path_ops operator
{
fields: ['data'],
using: 'gin',
operator: 'jsonb_path_ops'
},
// By default index name will be [table]_[fields]
// Creates a multi column partial index
{
name: 'public_by_author',
fields: ['author', 'status'],
where: {
status: 'public'
}
},
// A BTREE index with an ordered field
{
name: 'title_index',
using: 'BTREE',
fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
}
],
sequelize
});
Model usage
Data retrieval / Finders
Finder methods are intended to query data from the database. They do not return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for instances.
In this document we'll explore what finder methods can do:
find
- Search for one specific element in the database
// search for known ids
Project.findByPk(123).then(project => {
// project will be an instance of Project and stores the content of the table entry
// with id 123. if such an entry is not defined you will get null
})
// search for attributes
Project.findOne({ where: {title: 'aProject'} }).then(project => {
// project will be the first entry of the Projects table with the title 'aProject' || null
})
Project.findOne({
where: {title: 'aProject'},
attributes: ['id', ['name', 'title']]
}).then(project => {
// project will be the first entry of the Projects table with the title 'aProject' || null
// project.get('title') will contain the name of the project
})
findOrCreate
- Search for a specific element or create it if not available
The method findOrCreate
can be used to check if a certain element already exists in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created.
Let's assume we have an empty database with a User
model which has a username
and a job
.
where
option will be appended to defaults
for create case.
User
.findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
.then(([user, created]) => {
console.log(user.get({
plain: true
}))
console.log(created)
/*
findOrCreate returns an array containing the object that was found or created and a boolean that
will be true if a new object was created and false if not, like so:
[ {
username: 'sdepold',
job: 'Technical Lead JavaScript',
id: 1,
createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
},
true ]
In the example above, the array spread on line 3 divides the array into its 2 parts and passes them
as arguments to the callback function defined beginning at line 39, which treats them as "user" and
"created" in this case. (So "user" will be the object from index 0 of the returned array and
"created" will equal "true".)
*/
})
The code created a new instance. So when we already have an instance ...
User.create({ username: 'fnord', job: 'omnomnom' })
.then(() => User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}}))
.then(([user, created]) => {
console.log(user.get({
plain: true
}))
console.log(created)
/*
In this example, findOrCreate returns an array like this:
[ {
username: 'fnord',
job: 'omnomnom',
id: 2,
createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
},
false
]
The array returned by findOrCreate gets spread into its 2 parts by the array spread on line 3, and
the parts will be passed as 2 arguments to the callback function beginning on line 69, which will
then treat them as "user" and "created" in this case. (So "user" will be the object from index 0
of the returned array and "created" will equal "false".)
*/
})
... the existing entry will not be changed. See the job
of the second user, and the fact that created was false.
findAndCountAll
- Search for multiple elements in the database, returns both data and total count
This is a convenience method that combinesfindAll
and count
(see below) this is useful when dealing with queries related to pagination where you want to retrieve data with a limit
and offset
but also need to know the total number of records that match the query:
The success handler will always receive an object with two properties:
count
- an integer, total number records matching the where clause and other filters due to associationsrows
- an array of objects, the records matching the where clause and other filters due to associations, within the limit and offset range
Project
.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
})
.then(result => {
console.log(result.count);
console.log(result.rows);
});
It support includes. Only the includes that are marked as required
will be added to the count part:
Suppose you want to find all users who have a profile attached:
User.findAndCountAll({
include: [
{ model: Profile, required: true }
],
limit: 3
});
Because the include for Profile
has required
set it will result in an inner join, and only the users who have a profile will be counted. If we remove required
from the include, both users with and without profiles will be counted. Adding a where
clause to the include automatically makes it required:
User.findAndCountAll({
include: [
{ model: Profile, where: { active: true }}
],
limit: 3
});
The query above will only count users who have an active profile, because required
is implicitly set to true when you add a where clause to the include.
The options object that you pass to findAndCountAll
is the same as for findAll
(described below).
findAll
- Search for multiple elements in the database
// find multiple entries
Project.findAll().then(projects => {
// projects will be an array of all Project instances
})
// search for specific attributes - hash usage
Project.findAll({ where: { name: 'A Project' } }).then(projects => {
// projects will be an array of Project instances with the specified name
})
// search within a specific range
Project.findAll({ where: { id: [1,2,3] } }).then(projects => {
// projects will be an array of Projects having the id 1, 2 or 3
// this is actually doing an IN query
})
Project.findAll({
where: {
id: {
[Op.and]: {a: 5}, // AND (a = 5)
[Op.or]: [{a: 5}, {a: 6}], // (a = 5 OR a = 6)
[Op.gt]: 6, // id > 6
[Op.gte]: 6, // id >= 6
[Op.lt]: 10, // id < 10
[Op.lte]: 10, // id <= 10
[Op.ne]: 20, // id != 20
[Op.between]: [6, 10], // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
[Op.in]: [1, 2], // IN [1, 2]
[Op.notIn]: [1, 2], // NOT IN [1, 2]
[Op.like]: '%hat', // LIKE '%hat'
[Op.notLike]: '%hat', // NOT LIKE '%hat'
[Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only)
[Op.overlap]: [1, 2], // && [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2], // @> [1, 2] (PG array contains operator)
[Op.contained]: [1, 2], // <@ [1, 2] (PG array contained by operator)
[Op.any]: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)
},
status: {
[Op.not]: false // status NOT FALSE
}
}
})
Complex filtering / OR / NOT queries
It's possible to do complex where queries with multiple levels of nested AND, OR and NOT conditions. In order to do that you can use or
, and
or not
Operators
:
Project.findOne({
where: {
name: 'a project',
[Op.or]: [
{ id: [1,2,3] },
{ id: { [Op.gt]: 10 } }
]
}
})
Project.findOne({
where: {
name: 'a project',
id: {
[Op.or]: [
[1,2,3],
{ [Op.gt]: 10 }
]
}
}
})
Both pieces of code will generate the following:
SELECT *
FROM `Projects`
WHERE (
`Projects`.`name` = 'a project'
AND (`Projects`.`id` IN (1,2,3) OR `Projects`.`id` > 10)
)
LIMIT 1;
not
example:
Project.findOne({
where: {
name: 'a project',
[Op.not]: [
{ id: [1,2,3] },
{ array: { [Op.contains]: [3,4,5] } }
]
}
});
Will generate:
SELECT *
FROM `Projects`
WHERE (
`Projects`.`name` = 'a project'
AND NOT (`Projects`.`id` IN (1,2,3) OR `Projects`.`array` @> ARRAY[3,4,5]::INTEGER[])
)
LIMIT 1;
Manipulating the dataset with limit, offset, order and group
To get more relevant data, you can use limit, offset, order and grouping:
// limit the results of the query
Project.findAll({ limit: 10 })
// step over the first 10 elements
Project.findAll({ offset: 10 })
// step over the first 10 elements, and take 2
Project.findAll({ offset: 10, limit: 2 })
The syntax for grouping and ordering are equal, so below it is only explained with a single example for group, and the rest for order. Everything you see below can also be done for group
Project.findAll({order: [['title', 'DESC']]})
// yields ORDER BY title DESC
Project.findAll({group: 'name'})
// yields GROUP BY name
Notice how in the two examples above, the string provided is inserted verbatim into the query, i.e. column names are not escaped. When you provide a string to order/group, this will always be the case. If you want to escape column names, you should provide an array of arguments, even though you only want to order/group by a single column
something.findOne({
order: [
// will return `name`
['name'],
// will return `username` DESC
['username', 'DESC'],
// will return max(`age`)
sequelize.fn('max', sequelize.col('age')),
// will return max(`age`) DESC
[sequelize.fn('max', sequelize.col('age')), 'DESC'],
// will return otherfunction(`col1`, 12, 'lalala') DESC
[sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
// will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite!
[sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
]
})
To recap, the elements of the order/group array can be the following:
- String - will be quoted
- Array - first element will be quoted, second will be appended verbatim
- Object -
- Raw will be added verbatim without quoting
- Everything else is ignored, and if raw is not set, the query will fail
- Sequelize.fn and Sequelize.col returns functions and quoted column names
Raw queries
Sometimes you might be expecting a massive dataset that you just want to display, without manipulation. For each row you select, Sequelize creates an instance with functions for update, delete, get associations etc. If you have thousands of rows, this might take some time. If you only need the raw data and don't want to update anything, you can do like this to get the raw data.
// Are you expecting a massive dataset from the DB,
// and don't want to spend the time building DAOs for each entry?
// You can pass an extra query option to get the raw data instead:
Project.findAll({ where: { ... }, raw: true })
count
- Count the occurrences of elements in the database
There is also a method for counting database objects:
Project.count().then(c => {
console.log("There are " + c + " projects!")
})
Project.count({ where: {'id': {[Op.gt]: 25}} }).then(c => {
console.log("There are " + c + " projects with an id greater than 25.")
})
max
- Get the greatest value of a specific attribute within a specific table
And here is a method for getting the max value of an attribute
/*
Let's assume 3 person objects with an attribute age.
The first one is 10 years old,
the second one is 5 years old,
the third one is 40 years old.
*/
Project.max('age').then(max => {
// this will return 40
})
Project.max('age', { where: { age: { [Op.lt]: 20 } } }).then(max => {
// will be 10
})
min
- Get the least value of a specific attribute within a specific table
And here is a method for getting the min value of an attribute:
/*
Let's assume 3 person objects with an attribute age.
The first one is 10 years old,
the second one is 5 years old,
the third one is 40 years old.
*/
Project.min('age').then(min => {
// this will return 5
})
Project.min('age', { where: { age: { [Op.gt]: 5 } } }).then(min => {
// will be 10
})
sum
- Sum the value of specific attributes
In order to calculate the sum over a specific column of a table, you can
use the sum
method.
/*
Let's assume 3 person objects with an attribute age.
The first one is 10 years old,
the second one is 5 years old,
the third one is 40 years old.
*/
Project.sum('age').then(sum => {
// this will return 55
})
Project.sum('age', { where: { age: { [Op.gt]: 5 } } }).then(sum => {
// will be 50
})
Eager loading
When you are retrieving data from the database there is a fair chance that you also want to get associations with the same query - this is called eager loading. The basic idea behind that, is the use of the attribute include
when you are calling find
or findAll
. Lets assume the following setup:
class User extends Model {}
User.init({ name: Sequelize.STRING }, { sequelize, modelName: 'user' })
class Task extends Model {}
Task.init({ name: Sequelize.STRING }, { sequelize, modelName: 'task' })
class Tool extends Model {}
Tool.init({ name: Sequelize.STRING }, { sequelize, modelName: 'tool' })
Task.belongsTo(User)
User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' })
sequelize.sync().then(() => {
// this is where we continue ...
})
OK. So, first of all, let's load all tasks with their associated user.
Task.findAll({ include: [ User ] }).then(tasks => {
console.log(JSON.stringify(tasks))
/*
[{
"name": "A Task",
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"userId": 1,
"user": {
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z"
}
}]
*/
})
Notice that the accessor (the User
property in the resulting instance) is singular because the association is one-to-something.
Next thing: Loading of data with many-to-something associations!
User.findAll({ include: [ Task ] }).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"tasks": [{
"name": "A Task",
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"userId": 1
}]
}]
*/
})
Notice that the accessor (the Tasks
property in the resulting instance) is plural because the association is many-to-something.
If an association is aliased (using the as
option), you must specify this alias when including the model. Notice how the user's Tool
s are aliased as Instruments
above. In order to get that right you have to specify the model you want to load, as well as the alias:
User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}]
*/
})
You can also include by alias name by specifying a string that matches the association alias:
User.findAll({ include: ['Instruments'] }).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}]
*/
})
User.findAll({ include: [{ association: 'Instruments' }] }).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}]
*/
})
When eager loading we can also filter the associated model using where
. This will return all User
s in which the where
clause of Tool
model matches rows.
User.findAll({
include: [{
model: Tool,
as: 'Instruments',
where: { name: { [Op.like]: '%ooth%' } }
}]
}).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}],
[{
"name": "John Smith",
"id": 2,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}],
*/
})
When an eager loaded model is filtered using include.where
then include.required
is implicitly set to
true
. This means that an inner join is done returning parent models with any matching children.
Top level where with eagerly loaded models
To move the where conditions from an included model from the ON
condition to the top level WHERE
you can use the '$nested.column$'
syntax:
User.findAll({
where: {
'$Instruments.name$': { [Op.iLike]: '%ooth%' }
},
include: [{
model: Tool,
as: 'Instruments'
}]
}).then(users => {
console.log(JSON.stringify(users));
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}],
[{
"name": "John Smith",
"id": 2,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1
}]
}],
*/
Including everything
To include all attributes, you can pass a single object with all: true
:
User.findAll({ include: [{ all: true }]});
Including soft deleted records
In case you want to eager load soft deleted records you can do that by setting include.paranoid
to false
User.findAll({
include: [{
model: Tool,
where: { name: { [Op.like]: '%ooth%' } },
paranoid: false // query and loads the soft deleted records
}]
});
Ordering Eager Loaded Associations
In the case of a one-to-many relationship.
Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] });
Company.findAll({ include: [ Division ], order: [ [ Division, 'name', 'DESC' ] ] });
Company.findAll({
include: [ { model: Division, as: 'Div' } ],
order: [ [ { model: Division, as: 'Div' }, 'name' ] ]
});
Company.findAll({
include: [ { model: Division, as: 'Div' } ],
order: [ [ { model: Division, as: 'Div' }, 'name', 'DESC' ] ]
});
Company.findAll({
include: [ { model: Division, include: [ Department ] } ],
order: [ [ Division, Department, 'name' ] ]
});
In the case of many-to-many joins, you are also able to sort by attributes in the through table.
Company.findAll({
include: [ { model: Division, include: [ Department ] } ],
order: [ [ Division, DepartmentDivision, 'name' ] ]
});
Nested eager loading
You can use nested eager loading to load all related models of a related model:
User.findAll({
include: [
{model: Tool, as: 'Instruments', include: [
{model: Teacher, include: [ /* etc */]}
]}
]
}).then(users => {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{ // 1:M and N:M association
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"userId": 1,
"Teacher": { // 1:1 association
"name": "Jimi Hendrix"
}
}]
}]
*/
})
This will produce an outer join. However, a where
clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add required: false
.
User.findAll({
include: [{
model: Tool,
as: 'Instruments',
include: [{
model: Teacher,
where: {
school: "Woodstock Music School"
},
required: false
}]
}]
}).then(users => {
/* ... */
})
The query above will return all users, and all their instruments, but only those teachers associated with Woodstock Music School
.
Include all also supports nested loading:
User.findAll({ include: [{ all: true, nested: true }]});
Use right join for association
By default, associations are loaded using a left join, that is to say it only includes records from the parent table. You can change this behavior to a right join by passing the right
property, if the dialect you are using supports it. Currently, sqlite
does not support right joins.
Note: right
is only respected if required
is false.
User.findAll({
include: [{
model: Tool // will create a left join
}]
});
User.findAll({
include: [{
model: Tool,
right: true // will create a right join
}]
});
User.findAll({
include: [{
model: Tool,
required: true,
right: true // has no effect, will create an inner join
}]
});
User.findAll({
include: [{
model: Tool,
where: { name: { [Op.like]: '%ooth%' } },
right: true // has no effect, will create an inner join
}]
});
User.findAll({
include: [{
model: Tool,
where: { name: { [Op.like]: '%ooth%' } },
required: false
right: true // because we set `required` to false, this will create a right join
}]
});
Hooks
Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a beforeUpdate
hook.
Note: You can't use hooks with instances. Hooks are used with models.
For a full list of hooks, see Hooks file.
Order of Operations
(1)
beforeBulkCreate(instances, options)
beforeBulkDestroy(options)
beforeBulkUpdate(options)
(2)
beforeValidate(instance, options)
(-)
validate
(3)
afterValidate(instance, options)
- or -
validationFailed(instance, options, error)
(4)
beforeCreate(instance, options)
beforeDestroy(instance, options)
beforeUpdate(instance, options)
beforeSave(instance, options)
beforeUpsert(values, options)
(-)
create
destroy
update
(5)
afterCreate(instance, options)
afterDestroy(instance, options)
afterUpdate(instance, options)
afterSave(instance, options)
afterUpsert(created, options)
(6)
afterBulkCreate(instances, options)
afterBulkDestroy(options)
afterBulkUpdate(options)
Declaring Hooks
Arguments to hooks are passed by reference. This means, that you can change the values, and this will be reflected in the insert / update statement. A hook may contain async actions - in this case the hook function should return a promise.
There are currently three ways to programmatically add hooks:
// Method 1 via the .init() method
class User extends Model {}
User.init({
username: DataTypes.STRING,
mood: {
type: DataTypes.ENUM,
values: ['happy', 'sad', 'neutral']
}
}, {
hooks: {
beforeValidate: (user, options) => {
user.mood = 'happy';
},
afterValidate: (user, options) => {
user.username = 'Toni';
}
},
sequelize
});
// Method 2 via the .addHook() method
User.addHook('beforeValidate', (user, options) => {
user.mood = 'happy';
});
User.addHook('afterValidate', 'someCustomName', (user, options) => {
return Promise.reject(new Error("I'm afraid I can't let you do that!"));
});
// Method 3 via the direct method
User.beforeCreate((user, options) => {
return hashPassword(user.password).then(hashedPw => {
user.password = hashedPw;
});
});
User.afterValidate('myHookAfter', (user, options) => {
user.username = 'Toni';
});
Removing hooks
Only a hook with name param can be removed.
class Book extends Model {}
Book.init({
title: DataTypes.STRING
}, { sequelize });
Book.addHook('afterCreate', 'notifyUsers', (book, options) => {
// ...
});
Book.removeHook('afterCreate', 'notifyUsers');
You can have many hooks with same name. Calling .removeHook()
will remove all of them.
Global / universal hooks
Global hooks are hooks which are run for all models. They can define behaviours that you want for all your models, and are especially useful for plugins. They can be defined in two ways, which have slightly different semantics:
Default Hooks (Sequelize.options.define)
const sequelize = new Sequelize(..., {
define: {
hooks: {
beforeCreate: () => {
// Do stuff
}
}
}
});
This adds a default hook to all models, which is run if the model does not define its own beforeCreate
hook:
class User extends Model {}
User.init({}, { sequelize });
class Project extends Model {}
Project.init({}, {
hooks: {
beforeCreate: () => {
// Do other stuff
}
},
sequelize
});
User.create() // Runs the global hook
Project.create() // Runs its own hook (because the global hook is overwritten)
Permanent Hooks (Sequelize.addHook)
sequelize.addHook('beforeCreate', () => {
// Do stuff
});
This hook is always run before create, regardless of whether the model specifies its own beforeCreate
hook. Local hooks are always run before global hooks:
class User extends Model {}
User.init({}, { sequelize });
class Project extends Model {}
Project.init({}, {
hooks: {
beforeCreate: () => {
// Do other stuff
}
},
sequelize
});
User.create() // Runs the global hook
Project.create() // Runs its own hook, followed by the global hook
Permanent hooks may also be defined in Sequelize.options
:
new Sequelize(..., {
hooks: {
beforeCreate: () => {
// do stuff
}
}
});
Connection Hooks
Sequelize provides four hooks that are executed immediately before and after a database connection is obtained or released:
beforeConnect(config)
afterConnect(connection, config)
beforeDisconnect(connection)
afterDisconnect(connection)
These hooks can be useful if you need to asynchronously obtain database credentials, or need to directly access the low-level database connection after it has been created.
For example, we can asynchronously obtain a database password from a rotating token store, and mutate Sequelize's configuration object with the new credentials:
sequelize.beforeConnect((config) => {
return getAuthToken()
.then((token) => {
config.password = token;
});
});
These hooks may only be declared as a permanent global hook, as the connection pool is shared by all models.
Instance hooks
The following hooks will emit whenever you're editing a single object
beforeValidate
afterValidate or validationFailed
beforeCreate / beforeUpdate / beforeSave / beforeDestroy
afterCreate / afterUpdate / afterSave / afterDestroy
// ...define ...
User.beforeCreate(user => {
if (user.accessLevel > 10 && user.username !== "Boss") {
throw new Error("You can't grant this user an access level above 10!")
}
})
This example will return an error:
User.create({username: 'Not a Boss', accessLevel: 20}).catch(err => {
console.log(err); // You can't grant this user an access level above 10!
});
The following example would return successful:
User.create({username: 'Boss', accessLevel: 20}).then(user => {
console.log(user); // user object with username as Boss and accessLevel of 20
});
Model hooks
Sometimes you'll be editing more than one record at a time by utilizing the bulkCreate, update, destroy
methods on the model. The following will emit whenever you're using one of those methods:
beforeBulkCreate(instances, options)
beforeBulkUpdate(options)
beforeBulkDestroy(options)
afterBulkCreate(instances, options)
afterBulkUpdate(options)
afterBulkDestroy(options)
If you want to emit hooks for each individual record, along with the bulk hooks you can pass individualHooks: true
to the call.
WARNING: if you use individual hooks, all instances that are updated or destroyed will get loaded into memory before your hooks are called. The number of instances Sequelize can handle with individual hooks is limited by available memory.
Model.destroy({ where: {accessLevel: 0}, individualHooks: true});
// Will select all records that are about to be deleted and emit before- + after- Destroy on each instance
Model.update({username: 'Toni'}, { where: {accessLevel: 0}, individualHooks: true});
// Will select all records that are about to be updated and emit before- + after- Update on each instance
The options
argument of hook method would be the second argument provided to the corresponding method or its
cloned and extended version.
Model.beforeBulkCreate((records, {fields}) => {
// records = the first argument sent to .bulkCreate
// fields = one of the second argument fields sent to .bulkCreate
})
Model.bulkCreate([
{username: 'Toni'}, // part of records argument
{username: 'Tobi'} // part of records argument
], {fields: ['username']} // options parameter
)
Model.beforeBulkUpdate(({attributes, where}) => {
// where - in one of the fields of the clone of second argument sent to .update
// attributes - is one of the fields that the clone of second argument of .update would be extended with
})
Model.update({gender: 'Male'} /*attributes argument*/, { where: {username: 'Tom'}} /*where argument*/)
Model.beforeBulkDestroy(({where, individualHooks}) => {
// individualHooks - default of overridden value of extended clone of second argument sent to Model.destroy
// where - in one of the fields of the clone of second argument sent to Model.destroy
})
Model.destroy({ where: {username: 'Tom'}} /*where argument*/)
If you use Model.bulkCreate(...)
with the updateOnDuplicate
option, changes made in the hook to fields that aren't given in the updateOnDuplicate
array will not be persisted to the database. However it is possible to change the updateOnDuplicate option inside the hook if this is what you want.
// Bulk updating existing users with updateOnDuplicate option
Users.bulkCreate([
{ id: 1, isMember: true },
{ id: 2, isMember: false }
], {
updateOnDuplicate: ['isMember']
});
User.beforeBulkCreate((users, options) => {
for (const user of users) {
if (user.isMember) {
user.memberSince = new Date();
}
}
// Add memberSince to updateOnDuplicate otherwise the memberSince date wont be
// saved to the database
options.updateOnDuplicate.push('memberSince');
});
Associations
For the most part hooks will work the same for instances when being associated except a few things
- When using add/set functions the beforeUpdate/afterUpdate hooks will run.
- The only way to call beforeDestroy/afterDestroy hooks are on associations with
onDelete: 'cascade'
and the optionhooks: true
. For instance:
class Projects extends Model {}
Projects.init({
title: DataTypes.STRING
}, { sequelize });
class Tasks extends Model {}
Tasks.init({
title: DataTypes.STRING
}, { sequelize });
Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true });
Tasks.belongsTo(Projects);
This code will run beforeDestroy/afterDestroy on the Tasks table. Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute a
DELETE FROM `table` WHERE associatedIdentifier = associatedIdentifier.primaryKey
However, adding hooks: true
explicitly tells Sequelize that optimization is not of your concern and will perform a SELECT
on the associated objects and destroy each instance one by one in order to be able to call the hooks with the right parameters.
If your association is of type n:m
, you may be interested in firing hooks on the through model when using the remove
call. Internally, sequelize is using Model.destroy
resulting in calling the bulkDestroy
instead of the before/afterDestroy
hooks on each through instance.
This can be simply solved by passing {individualHooks: true}
to the remove
call, resulting on each hook to be called on each removed through instance object.
A Note About Transactions
Note that many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction _is_ specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:
// Here we use the promise-style of async hooks rather than
// the callback.
User.addHook('afterCreate', (user, options) => {
// 'transaction' will be available in options.transaction
// This operation will be part of the same transaction as the
// original User.create call.
return User.update({
mood: 'sad'
}, {
where: {
id: user.id
},
transaction: options.transaction
});
});
sequelize.transaction(transaction => {
User.create({
username: 'someguy',
mood: 'happy',
transaction
});
});
If we had not included the transaction option in our call to User.update
in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.
Internal Transactions
It is very important to recognize that sequelize may make use of transactions internally for certain operations such as Model.findOrCreate
. If your hook functions execute read or write operations that rely on the object's presence in the database, or modify the object's stored values like the example in the preceding section, you should always specify { transaction: options.transaction }
.
If the hook has been called in the process of a transacted operation, this makes sure that your dependent read/write is a part of that same transaction. If the hook is not transacted, you have simply specified { transaction: null }
and can expect the default behaviour.
Querying
Attributes
To select only some attributes, you can use the attributes
option. Most often, you pass an array:
Model.findAll({
attributes: ['foo', 'bar']
});
SELECT foo, bar ...
Attributes can be renamed using a nested array:
Model.findAll({
attributes: ['foo', ['bar', 'baz']]
});
SELECT foo, bar AS baz ...
You can use sequelize.fn
to do aggregations:
Model.findAll({
attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
});
SELECT COUNT(hats) AS no_hats ...
When using aggregation function, you must give it an alias to be able to access it from the model. In the example above you can get the number of hats with instance.get('no_hats')
.
Sometimes it may be tiresome to list all the attributes of the model if you only want to add an aggregation:
// This is a tiresome way of getting the number of hats...
Model.findAll({
attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
});
// This is shorter, and less error prone because it still works if you add / remove attributes
Model.findAll({
attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }
});
SELECT id, foo, bar, baz, quz, COUNT(hats) AS no_hats ...
Similarly, it's also possible to remove a selected few attributes:
Model.findAll({
attributes: { exclude: ['baz'] }
});
SELECT id, foo, bar, quz ...
Where
Whether you are querying with findAll/find or doing bulk updates/destroys you can pass a where
object to filter the query.
where
generally takes an object from attribute:value pairs, where value can be primitives for equality matches or keyed objects for other operators.
It's also possible to generate complex AND/OR conditions by nesting sets of or
and and
Operators
.
Basics
const Op = Sequelize.Op;
Post.findAll({
where: {
authorId: 2
}
});
// SELECT * FROM post WHERE authorId = 2
Post.findAll({
where: {
authorId: 12,
status: 'active'
}
});
// SELECT * FROM post WHERE authorId = 12 AND status = 'active';
Post.findAll({
where: {
[Op.or]: [{authorId: 12}, {authorId: 13}]
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Post.findAll({
where: {
authorId: {
[Op.or]: [12, 13]
}
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Post.destroy({
where: {
status: 'inactive'
}
});
// DELETE FROM post WHERE status = 'inactive';
Post.update({
updatedAt: null,
}, {
where: {
deletedAt: {
[Op.ne]: null
}
}
});
// UPDATE post SET updatedAt = null WHERE deletedAt NOT NULL;
Post.findAll({
where: sequelize.where(sequelize.fn('char_length', sequelize.col('status')), 6)
});
// SELECT * FROM post WHERE char_length(status) = 6;
Operators
Sequelize exposes symbol operators that can be used for to create more complex comparisons -
const Op = Sequelize.Op
[Op.and]: [{a: 5}, {b: 6}] // (a = 5) AND (b = 6)
[Op.or]: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
[Op.gt]: 6, // > 6
[Op.gte]: 6, // >= 6
[Op.lt]: 10, // < 10
[Op.lte]: 10, // <= 10
[Op.ne]: 20, // != 20
[Op.eq]: 3, // = 3
[Op.is]: null // IS NULL
[Op.not]: true, // IS NOT TRUE
[Op.between]: [6, 10], // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
[Op.in]: [1, 2], // IN [1, 2]
[Op.notIn]: [1, 2], // NOT IN [1, 2]
[Op.like]: '%hat', // LIKE '%hat'
[Op.notLike]: '%hat' // NOT LIKE '%hat'
[Op.iLike]: '%hat' // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat' // NOT ILIKE '%hat' (PG only)
[Op.startsWith]: 'hat' // LIKE 'hat%'
[Op.endsWith]: 'hat' // LIKE '%hat'
[Op.substring]: 'hat' // LIKE '%hat%'
[Op.regexp]: '^[h|a|t]' // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
[Op.notRegexp]: '^[h|a|t]' // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
[Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (PG only)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (PG only)
[Op.like]: { [Op.any]: ['cat', 'hat']}
// LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
[Op.overlap]: [1, 2] // && [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2] // @> [1, 2] (PG array contains operator)
[Op.contained]: [1, 2] // <@ [1, 2] (PG array contained by operator)
[Op.any]: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)
[Op.col]: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example
[Op.gt]: { [Op.all]: literal('SELECT 1') }
// > ALL (SELECT 1)
Range Operators
Range types can be queried with all supported operators.
Keep in mind, the provided range value can define the bound inclusion/exclusion as well.
// All the above equality and inequality operators plus the following:
[Op.contains]: 2 // @> '2'::integer (PG range contains element operator)
[Op.contains]: [1, 2] // @> [1, 2) (PG range contains range operator)
[Op.contained]: [1, 2] // <@ [1, 2) (PG range is contained by operator)
[Op.overlap]: [1, 2] // && [1, 2) (PG range overlap (have points in common) operator)
[Op.adjacent]: [1, 2] // -|- [1, 2) (PG range is adjacent to operator)
[Op.strictLeft]: [1, 2] // << [1, 2) (PG range strictly left of operator)
[Op.strictRight]: [1, 2] // >> [1, 2) (PG range strictly right of operator)
[Op.noExtendRight]: [1, 2] // &< [1, 2) (PG range does not extend to the right of operator)
[Op.noExtendLeft]: [1, 2] // &> [1, 2) (PG range does not extend to the left of operator)
Combinations
const Op = Sequelize.Op;
{
rank: {
[Op.or]: {
[Op.lt]: 1000,
[Op.eq]: null
}
}
}
// rank < 1000 OR rank IS NULL
{
createdAt: {
[Op.lt]: new Date(),
[Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
}
}
// createdAt < [timestamp] AND createdAt > [timestamp]
{
[Op.or]: [
{
title: {
[Op.like]: 'Boat%'
}
},
{
description: {
[Op.like]: '%boat%'
}
}
]
}
// title LIKE 'Boat%' OR description LIKE '%boat%'
Operators Aliases
Sequelize allows setting specific strings as aliases for operators. With v5 this will give you deprecation warning.
const Op = Sequelize.Op;
const operatorsAliases = {
$gt: Op.gt
}
const connection = new Sequelize(db, user, pass, { operatorsAliases })
[Op.gt]: 6 // > 6
$gt: 6 // same as using Op.gt (> 6)
Operators security
By default Sequelize will use Symbol operators. Using Sequelize without any aliases improves security. Not having any string aliases will make it extremely unlikely that operators could be injected but you should always properly validate and sanitize user input.
Some frameworks automatically parse user input into js objects and if you fail to sanitize your input it might be possible to inject an Object with string operators to Sequelize.
For better security it is highly advised to use symbol operators from Sequelize.Op
like Op.and
/ Op.or
in your code and not depend on any string based operators like $and
/ $or
at all. You can limit alias your application will need by setting operatorsAliases
option, remember to sanitize user input especially when you are directly passing them to Sequelize methods.
const Op = Sequelize.Op;
//use sequelize without any operators aliases
const connection = new Sequelize(db, user, pass, { operatorsAliases: false });
//use sequelize with only alias for $and => Op.and
const connection2 = new Sequelize(db, user, pass, { operatorsAliases: { $and: Op.and } });
Sequelize will warn you if you're using the default aliases and not limiting them if you want to keep using all default aliases (excluding legacy ones) without the warning you can pass the following operatorsAliases option -
const Op = Sequelize.Op;
const operatorsAliases = {
$eq: Op.eq,
$ne: Op.ne,
$gte: Op.gte,
$gt: Op.gt,
$lte: Op.lte,
$lt: Op.lt,
$not: Op.not,
$in: Op.in,
$notIn: Op.notIn,
$is: Op.is,
$like: Op.like,
$notLike: Op.notLike,
$iLike: Op.iLike,
$notILike: Op.notILike,
$regexp: Op.regexp,
$notRegexp: Op.notRegexp,
$iRegexp: Op.iRegexp,
$notIRegexp: Op.notIRegexp,
$between: Op.between,
$notBetween: Op.notBetween,
$overlap: Op.overlap,
$contains: Op.contains,
$contained: Op.contained,
$adjacent: Op.adjacent,
$strictLeft: Op.strictLeft,
$strictRight: Op.strictRight,
$noExtendRight: Op.noExtendRight,
$noExtendLeft: Op.noExtendLeft,
$and: Op.and,
$or: Op.or,
$any: Op.any,
$all: Op.all,
$values: Op.values,
$col: Op.col
};
const connection = new Sequelize(db, user, pass, { operatorsAliases });
JSON
The JSON data type is supported by the PostgreSQL, SQLite, MySQL and MariaDB dialects only.
PostgreSQL
The JSON data type in PostgreSQL stores the value as plain text, as opposed to binary representation. If you simply want to store and retrieve a JSON representation, using JSON will take less disk space and less time to build from its input representation. However, if you want to do any operations on the JSON value, you should prefer the JSONB data type described below.
MSSQL
MSSQL does not have a JSON data type, however it does provide support for JSON stored as strings through certain functions since SQL Server 2016. Using these functions, you will be able to query the JSON stored in the string, but any returned values will need to be parsed separately.
// ISJSON - to test if a string contains valid JSON
User.findAll({
where: sequelize.where(sequelize.fn('ISJSON', sequelize.col('userDetails')), 1)
})
// JSON_VALUE - extract a scalar value from a JSON string
User.findAll({
attributes: [[ sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), 'address line 1']]
})
// JSON_VALUE - query a scalar value from a JSON string
User.findAll({
where: sequelize.where(sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), '14, Foo Street')
})
// JSON_QUERY - extract an object or array
User.findAll({
attributes: [[ sequelize.fn('JSON_QUERY', sequelize.col('userDetails'), '$.address'), 'full address']]
})
JSONB
JSONB can be queried in three different ways.
Nested object
{
meta: {
video: {
url: {
[Op.ne]: null
}
}
}
}
Nested key
{
"meta.audio.length": {
[Op.gt]: 20
}
}
Containment
{
"meta": {
[Op.contains]: {
site: {
url: 'http://google.com'
}
}
}
}
Relations / Associations
// Find all projects with a least one task where task.state === project.state
Project.findAll({
include: [{
model: Task,
where: { state: Sequelize.col('project.state') }
}]
})
Pagination / Limiting
// Fetch 10 instances/rows
Project.findAll({ limit: 10 })
// Skip 8 instances/rows
Project.findAll({ offset: 8 })
// Skip 5 instances and fetch the 5 after that
Project.findAll({ offset: 5, limit: 5 })
Ordering
order
takes an array of items to order the query by or a sequelize method. Generally you will want to use a tuple/array of either attribute, direction or just direction to ensure proper escaping.
Subtask.findAll({
order: [
// Will escape title and validate DESC against a list of valid direction parameters
['title', 'DESC'],
// Will order by max(age)
sequelize.fn('max', sequelize.col('age')),
// Will order by max(age) DESC
[sequelize.fn('max', sequelize.col('age')), 'DESC'],
// Will order by otherfunction(`col1`, 12, 'lalala') DESC
[sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
// Will order an associated model's created_at using the model name as the association's name.
[Task, 'createdAt', 'DESC'],
// Will order through an associated model's created_at using the model names as the associations' names.
[Task, Project, 'createdAt', 'DESC'],
// Will order by an associated model's created_at using the name of the association.
['Task', 'createdAt', 'DESC'],
// Will order by a nested associated model's created_at using the names of the associations.
['Task', 'Project', 'createdAt', 'DESC'],
// Will order by an associated model's created_at using an association object. (preferred method)
[Subtask.associations.Task, 'createdAt', 'DESC'],
// Will order by a nested associated model's created_at using association objects. (preferred method)
[Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
// Will order by an associated model's created_at using a simple association object.
[{model: Task, as: 'Task'}, 'createdAt', 'DESC'],
// Will order by a nested associated model's created_at simple association objects.
[{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
]
// Will order by max age descending
order: sequelize.literal('max(age) DESC')
// Will order by max age ascending assuming ascending is the default order when direction is omitted
order: sequelize.fn('max', sequelize.col('age'))
// Will order by age ascending assuming ascending is the default order when direction is omitted
order: sequelize.col('age')
// Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
order: sequelize.random()
})
Table Hint
tableHint
can be used to optionally pass a table hint when using mssql. The hint must be a value from Sequelize.TableHints
and should only be used when absolutely necessary. Only a single table hint is currently supported per query.
Table hints override the default behavior of mssql query optimizer by specifying certain options. They only affect the table or view referenced in that clause.
const TableHints = Sequelize.TableHints;
Project.findAll({
// adding the table hint NOLOCK
tableHint: TableHints.NOLOCK
// this will generate the SQL 'WITH (NOLOCK)'
})
Index Hints
indexHints
can be used to optionally pass index hints when using mysql. The hint type must be a value from Sequelize.IndexHints
and the values should reference existing indexes.
Index hints override the default behavior of the mysql query optimizer.
Project.findAll({
indexHints: [
{ type: IndexHints.USE, values: ['index_project_on_name'] }
],
where: {
id: {
[Op.gt]: 623
},
name: {
[Op.like]: 'Foo %'
}
}
})
Will generate a mysql query that looks like this:
SELECT * FROM Project USE INDEX (index_project_on_name) WHERE name LIKE 'FOO %' AND id > 623;
Sequelize.IndexHints
includes USE
, FORCE
, and IGNORE
.
See Issue #9421 for the original API proposal.
Instances
Building a non-persistent instance
In order to create instances of defined classes just do as follows. You might recognize the syntax if you coded Ruby in the past. Using the build
-method will return an unsaved object, which you explicitly have to save.
const project = Project.build({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
})
const task = Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
})
Built instances will automatically get default values when they were defined:
// first define the model
class Task extends Model {}
Task.init({
title: Sequelize.STRING,
rating: { type: Sequelize.TINYINT, defaultValue: 3 }
}, { sequelize, modelName: 'task' });
// now instantiate an object
const task = Task.build({title: 'very important task'})
task.title // ==> 'very important task'
task.rating // ==> 3
To get it stored in the database, use the save
-method and catch the events ... if needed:
project.save().then(() => {
// my nice callback stuff
})
task.save().catch(error => {
// mhhh, wth!
})
// you can also build, save and access the object with chaining:
Task
.build({ title: 'foo', description: 'bar', deadline: new Date() })
.save()
.then(anotherTask => {
// you can now access the currently saved task with the variable anotherTask... nice!
})
.catch(error => {
// Ooops, do some error-handling
})
Creating persistent instances
While an instance created with .build()
requires an explicit .save()
call to be stored in the database, .create()
omits that requirement altogether and automatically stores your instance's data once called.
Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => {
// you can now access the newly created task via the variable task
})
It is also possible to define which attributes can be set via the create method. This can be especially very handy if you create database entries based on a form which can be filled by a user. Using that would for example allow you to restrict the User
model to set only a username and an address but not an admin flag:
User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => {
// let's assume the default of isAdmin is false:
console.log(user.get({
plain: true
})) // => { username: 'barfooz', isAdmin: false }
})
Updating / Saving / Persisting an instance
Now lets change some values and save changes to the database... There are two ways to do that:
// way 1
task.title = 'a very different title now'
task.save().then(() => {})
// way 2
task.update({
title: 'a very different title now'
}).then(() => {})
It's also possible to define which attributes should be saved when calling save
, by passing an array of column names. This is useful when you set attributes based on a previously defined object. E.g. if you get the values of an object via a form of a web app. Furthermore this is used internally for update
. This is how it looks like:
task.title = 'foooo'
task.description = 'baaaaaar'
task.save({fields: ['title']}).then(() => {
// title will now be 'foooo' but description is the very same as before
})
// The equivalent call using update looks like this:
task.update({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(() => {
// title will now be 'foooo' but description is the very same as before
})
When you call save
without changing any attribute, this method will execute nothing;
Destroying / Deleting persistent instances
Once you created an object and got a reference to it, you can delete it from the database. The relevant method is destroy
:
Task.create({ title: 'a task' }).then(task => {
// now you see me...
return task.destroy();
}).then(() => {
// now i'm gone :)
})
If the paranoid
options is true, the object will not be deleted, instead the deletedAt
column will be set to the current timestamp. To force the deletion, you can pass force: true
to the destroy call:
task.destroy({ force: true })
After an object is soft deleted in paranoid
mode, you will not be able to create a new instance with the same primary key
until you have force-deleted the old instance.
Restoring soft-deleted instances
If you have soft-deleted an instance of a model with paranoid: true
, and would like to undo the deletion, use the restore
method:
Task.create({ title: 'a task' }).then(task => {
// now you see me...
return task.destroy();
}).then((task) => {
// now i'm gone, but wait...
return task.restore();
})
Working in bulk (creating, updating and destroying multiple rows at once)
In addition to updating a single instance, you can also create, update, and delete multiple instances at once. The functions you are looking for are called
Model.bulkCreate
Model.update
Model.destroy
Since you are working with multiple models, the callbacks will not return DAO instances. BulkCreate will return an array of model instances/DAOs, they will however, unlike create
, not have the resulting values of autoIncrement attributes.update
and destroy
will return the number of affected rows.
First lets look at bulkCreate
User.bulkCreate([
{ username: 'barfooz', isAdmin: true },
{ username: 'foo', isAdmin: true },
{ username: 'bar', isAdmin: false }
]).then(() => { // Notice: There are no arguments here, as of right now you'll have to...
return User.findAll();
}).then(users => {
console.log(users) // ... in order to get the array of user objects
})
Insert several rows and return all columns (Postgres only):
User.bulkCreate([
{ username: 'barfooz', isAdmin: true },
{ username: 'foo', isAdmin: true },
{ username: 'bar', isAdmin: false }
], { returning: true }) // will return all columns for each row inserted
.then((result) => {
console.log(result);
});
Insert several rows and return specific columns (Postgres only):
User.bulkCreate([
{ username: 'barfooz', isAdmin: true },
{ username: 'foo', isAdmin: true },
{ username: 'bar', isAdmin: false }
], { returning: ['username'] }) // will return only the specified columns for each row inserted
.then((result) => {
console.log(result);
});
To update several rows at once:
Task.bulkCreate([
{subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'}
]).then(() => {
return Task.update(
{ status: 'inactive' }, /* set attributes' value */
{ where: { subject: 'programming' }} /* where criteria */
);
}).then(([affectedCount, affectedRows]) => {
// Notice that affectedRows will only be defined in dialects which support returning: true
// affectedCount will be 2
return Task.findAll();
}).then(tasks => {
console.log(tasks) // the 'programming' tasks will both have a status of 'inactive'
})
And delete them:
Task.bulkCreate([
{subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'}
]).then(() => {
return Task.destroy({
where: {
subject: 'programming'
},
truncate: true /* this will ignore where and truncate the table instead */
});
}).then(affectedRows => {
// affectedRows will be 2
return Task.findAll();
}).then(tasks => {
console.log(tasks) // no programming, just reading :(
})
If you are accepting values directly from the user, it might be beneficial to limit the columns that you want to actually insert.bulkCreate()
accepts an options object as the second parameter. The object can have a fields
parameter, (an array) to let it know which fields you want to build explicitly
User.bulkCreate([
{ username: 'foo' },
{ username: 'bar', admin: true}
], { fields: ['username'] }).then(() => {
// nope bar, you can't be admin!
})
bulkCreate
was originally made to be a mainstream/fast way of inserting records, however, sometimes you want the luxury of being able to insert multiple rows at once without sacrificing model validations even when you explicitly tell Sequelize which columns to sift through. You can do by adding a validate: true
property to the options object.
class Tasks extends Model {}
Tasks.init({
name: {
type: Sequelize.STRING,
validate: {
notNull: { args: true, msg: 'name cannot be null' }
}
},
code: {
type: Sequelize.STRING,
validate: {
len: [3, 10]
}
}
}, { sequelize, modelName: 'tasks' })
Tasks.bulkCreate([
{name: 'foo', code: '123'},
{code: '1234'},
{name: 'bar', code: '1'}
], { validate: true }).catch(errors => {
/* console.log(errors) would look like:
[
{ record:
...
name: 'SequelizeBulkRecordError',
message: 'Validation error',
errors:
{ name: 'SequelizeValidationError',
message: 'Validation error',
errors: [Object] } },
{ record:
...
name: 'SequelizeBulkRecordError',
message: 'Validation error',
errors:
{ name: 'SequelizeValidationError',
message: 'Validation error',
errors: [Object] } }
]
*/
})
Values of an instance
If you log an instance you will notice, that there is a lot of additional stuff. In order to hide such stuff and reduce it to the very interesting information, you can use theget
-attribute. Calling it with the option plain
= true will only return the values of an instance.
Person.create({
name: 'Rambow',
firstname: 'John'
}).then(john => {
console.log(john.get({
plain: true
}))
})
// result:
// { name: 'Rambow',
// firstname: 'John',
// id: 1,
// createdAt: Tue, 01 May 2012 19:12:16 GMT,
// updatedAt: Tue, 01 May 2012 19:12:16 GMT
// }
Hint:You can also transform an instance into JSON by using JSON.stringify(instance)
. This will basically return the very same as values
.
Reloading instances
If you need to get your instance in sync, you can use the methodreload
. It will fetch the current data from the database and overwrite the attributes of the model on which the method has been called on.
Person.findOne({ where: { name: 'john' } }).then(person => {
person.name = 'jane'
console.log(person.name) // 'jane'
person.reload().then(() => {
console.log(person.name) // 'john'
})
})
Incrementing
In order to increment values of an instance without running into concurrency issues, you may use increment
.
First of all you can define a field and the value you want to add to it.
User.findByPk(1).then(user => {
return user.increment('my-integer-field', {by: 2})
}).then(user => {
// Postgres will return the updated user by default (unless disabled by setting { returning: false })
// In other dialects, you'll want to call user.reload() to get the updated instance...
})
Second, you can define multiple fields and the value you want to add to them.
User.findByPk(1).then(user => {
return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)
Third, you can define an object containing fields and its increment values.
User.findByPk(1).then(user => {
return user.increment({
'my-integer-field': 2,
'my-very-other-field': 3
})
}).then(/* ... */)
Decrementing
In order to decrement values of an instance without running into concurrency issues, you may use decrement
.
First of all you can define a field and the value you want to add to it.
User.findByPk(1).then(user => {
return user.decrement('my-integer-field', {by: 2})
}).then(user => {
// Postgres will return the updated user by default (unless disabled by setting { returning: false })
// In other dialects, you'll want to call user.reload() to get the updated instance...
})
Second, you can define multiple fields and the value you want to add to them.
User.findByPk(1).then(user => {
return user.decrement([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)
Third, you can define an object containing fields and its decrement values.
User.findByPk(1).then(user => {
return user.decrement({
'my-integer-field': 2,
'my-very-other-field': 3
})
}).then(/* ... */)
Associations
This section describes the various association types in sequelize. There are four type of associations available in Sequelize
- BelongsTo
- HasOne
- HasMany
- BelongsToMany
Basic Concepts
Source & Target
Let's first begin with a basic concept that you will see used in most associations, source and target model. Suppose you are trying to add an association between two Models. Here we are adding a hasOne
association between User
and Project
.
class User extends Model {}
User.init({
name: Sequelize.STRING,
email: Sequelize.STRING
}, {
sequelize,
modelName: 'user'
});
class Project extends Model {}
Project.init({
name: Sequelize.STRING
}, {
sequelize,
modelName: 'project'
});
User.hasOne(Project);
User
model (the model that the function is being invoked on) is the source. Project
model (the model being passed as an argument) is the target.
Foreign Keys
When you create associations between your models in sequelize, foreign key references with constraints will automatically be created. The setup below:
class Task extends Model {}
Task.init({ title: Sequelize.STRING }, { sequelize, modelName: 'task' });
class User extends Model {}
User.init({ username: Sequelize.STRING }, { sequelize, modelName: 'user' });
User.hasMany(Task); // Will add userId to Task model
Task.belongsTo(User); // Will also add userId to Task model
Will generate the following SQL:
CREATE TABLE IF NOT EXISTS "users" (
"id" SERIAL,
"username" VARCHAR(255),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY ("id")
);
CREATE TABLE IF NOT EXISTS "tasks" (
"id" SERIAL,
"title" VARCHAR(255),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"userId" INTEGER REFERENCES "users" ("id") ON DELETE
SET
NULL ON UPDATE CASCADE,
PRIMARY KEY ("id")
);
The relation between tasks
and users
model injects the userId
foreign key on tasks
table, and marks it as a reference to the users
table. By default userId
will be set to NULL
if the referenced user is deleted, and updated if the id of the userId
updated. These options can be overridden by passing onUpdate
and onDelete
options to the association calls. The validation options are RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
.
For 1:1 and 1:m associations the default option is SET NULL
for deletion, and CASCADE
for updates. For n:m, the default for both is CASCADE
. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.
underscored option
Sequelize allow setting underscored
option for Model. When true
this option will set the
field
option on all attributes to the underscored version of its name. This also applies to
foreign keys generated by associations.
Let's modify last example to use underscored
option.
class Task extends Model {}
Task.init({
title: Sequelize.STRING
}, {
underscored: true,
sequelize,
modelName: 'task'
});
class User extends Model {}
User.init({
username: Sequelize.STRING
}, {
underscored: true,
sequelize,
modelName: 'user'
});
// Will add userId to Task model, but field will be set to `user_id`
// This means column name will be `user_id`
User.hasMany(Task);
// Will also add userId to Task model, but field will be set to `user_id`
// This means column name will be `user_id`
Task.belongsTo(User);
Will generate the following SQL:
CREATE TABLE IF NOT EXISTS "users" (
"id" SERIAL,
"username" VARCHAR(255),
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY ("id")
);
CREATE TABLE IF NOT EXISTS "tasks" (
"id" SERIAL,
"title" VARCHAR(255),
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"user_id" INTEGER REFERENCES "users" ("id") ON DELETE
SET
NULL ON UPDATE CASCADE,
PRIMARY KEY ("id")
);
With the underscored option attributes injected to model are still camel cased but field
option is set to their underscored version.
Cyclic dependencies & Disabling constraints
Adding constraints between tables means that tables must be created in the database in a certain order, when using sequelize.sync
. If Task
has a reference to User
, the users
table must be created before the tasks
table can be created. This can sometimes lead to circular references, where sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has a reference to its current version.
class Document extends Model {}
Document.init({
author: Sequelize.STRING
}, { sequelize, modelName: 'document' });
class Version extends Model {}
Version.init({
timestamp: Sequelize.DATE
}, { sequelize, modelName: 'version' });
Document.hasMany(Version); // This adds documentId attribute to version
Document.belongsTo(Version, {
as: 'Current',
foreignKey: 'currentVersionId'
}); // This adds currentVersionId attribute to document
However, the code above will result in the following error: Cyclic dependency found. documents is dependent of itself. Dependency chain: documents -> versions => documents
.
In order to alleviate that, we can pass constraints: false
to one of the associations:
Document.hasMany(Version);
Document.belongsTo(Version, {
as: 'Current',
foreignKey: 'currentVersionId',
constraints: false
});
Which will allow us to sync the tables correctly:
CREATE TABLE IF NOT EXISTS "documents" (
"id" SERIAL,
"author" VARCHAR(255),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"currentVersionId" INTEGER,
PRIMARY KEY ("id")
);
CREATE TABLE IF NOT EXISTS "versions" (
"id" SERIAL,
"timestamp" TIMESTAMP WITH TIME ZONE,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"documentId" INTEGER REFERENCES "documents" ("id") ON DELETE
SET
NULL ON UPDATE CASCADE,
PRIMARY KEY ("id")
);
Enforcing a foreign key reference without constraints
Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.
class Trainer extends Model {}
Trainer.init({
firstName: Sequelize.STRING,
lastName: Sequelize.STRING
}, { sequelize, modelName: 'trainer' });
// Series will have a trainerId = Trainer.id foreign reference key
// after we call Trainer.hasMany(series)
class Series extends Model {}
Series.init({
title: Sequelize.STRING,
subTitle: Sequelize.STRING,
description: Sequelize.TEXT,
// Set FK relationship (hasMany) with `Trainer`
trainerId: {
type: Sequelize.INTEGER,
references: {
model: Trainer,
key: 'id'
}
}
}, { sequelize, modelName: 'series' });
// Video will have seriesId = Series.id foreign reference key
// after we call Series.hasOne(Video)
class Video extends Model {}
Video.init({
title: Sequelize.STRING,
sequence: Sequelize.INTEGER,
description: Sequelize.TEXT,
// set relationship (hasOne) with `Series`
seriesId: {
type: Sequelize.INTEGER,
references: {
model: Series, // Can be both a string representing the table name or a Sequelize model
key: 'id'
}
}
}, { sequelize, modelName: 'video' });
Series.hasOne(Video);
Trainer.hasMany(Series);
One-To-One associations
One-To-One associations are associations between exactly two models connected by a single foreign key.
BelongsTo
BelongsTo associations are associations where the foreign key for the one-to-one relation exists on the source model.
A simple example would be a Player being part of a Team with the foreign key on the player.
class Player extends Model {}
Player.init({/* attributes */}, { sequelize, modelName: 'player' });
class Team extends Model {}
Team.init({/* attributes */}, { sequelize, modelName: 'team' });
Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team
Foreign keys
By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name.
The default casing is camelCase
. If the source model is configured with underscored: true
the foreignKey will be created with field snake_case
.
class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });
// will add companyId to user
User.belongsTo(Company);
class User extends Model {}
User.init({/* attributes */}, { underscored: true, sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({
uuid: {
type: Sequelize.UUID,
primaryKey: true
}
}, { sequelize, modelName: 'company' });
// will add companyUuid to user with field company_uuid
User.belongsTo(Company);
In cases where as
has been defined it will be used in place of the target model name.
class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class UserRole extends Model {}
UserRole.init({/* attributes */}, { sequelize, modelName: 'userRole' });
User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId
In all cases the default foreign key can be overwritten with the foreignKey
option.
When the foreign key option is used, Sequelize will use it as-is:
class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });
User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User
Target keys
The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the targetKey
option.
class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });
User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User
HasOne
HasOne associations are associations where the foreign key for the one-to-one relation exists on the target model.
class User extends Model {}
User.init({/* ... */}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({/* ... */}, { sequelize, modelName: 'project' })
// One-way associations
Project.hasOne(User)
/*
In this example hasOne will add an attribute projectId to the User model!
Furthermore, Project.prototype will gain the methods getUser and setUser according
to the first parameter passed to define. If you have underscore style
enabled, the added attribute will be project_id instead of projectId.
The foreign key will be placed on the users table.
You can also define the foreign key, e.g. if you already have an existing
database and want to work on it:
*/
Project.hasOne(User, { foreignKey: 'initiator_id' })
/*
Because Sequelize will use the model's name (first parameter of define) for
the accessor methods, it is also possible to pass a special option to hasOne:
*/
Project.hasOne(User, { as: 'Initiator' })
// Now you will get Project.getInitiator and Project.setInitiator
// Or let's define some self references
class Person extends Model {}
Person.init({ /* ... */}, { sequelize, modelName: 'person' })
Person.hasOne(Person, {as: 'Father'})
// this will add the attribute FatherId to Person
// also possible:
Person.hasOne(Person, {as: 'Father', foreignKey: 'DadId'})
// this will add the attribute DadId to Person
// In both cases you will be able to do:
Person.setFather
Person.getFather
// If you need to join a table twice you can double join the same table
Team.hasOne(Game, {as: 'HomeTeam', foreignKey : 'homeTeamId'});
Team.hasOne(Game, {as: 'AwayTeam', foreignKey : 'awayTeamId'});
Game.belongsTo(Team);
Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.
Source keys
The source key is the attribute on the source model that the foreign key attribute on the target model points to. By default the source key for a hasOne
relation will be the source model's primary attribute. To use a custom attribute, use the sourceKey
option.
class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });
// Adds companyName attribute to User
// Use name attribute from Company as source attribute
Company.hasOne(User, {foreignKey: 'companyName', sourceKey: 'name'});
Difference between HasOne and BelongsTo
In Sequelize 1:1 relationship can be set using HasOne and BelongsTo. They are suitable for different scenarios. Lets study this difference using an example.
Suppose we have two tables to link Player and Team. Lets define their models.
class Player extends Model {}
Player.init({/* attributes */}, { sequelize, modelName: 'player' })
class Team extends Model {}
Team.init({/* attributes */}, { sequelize, modelName: 'team' });
When we link two models in Sequelize we can refer them as pairs of source and target models. Like this
Having Player as the source and Team as the target
Player.belongsTo(Team);
//Or
Player.hasOne(Team);
Having Team as the source and Player as the target
Team.belongsTo(Player);
//Or
Team.hasOne(Player);
HasOne and BelongsTo insert the association key in different models from each other. HasOne inserts the association key in target model whereas BelongsTo inserts the association key in the source model.
Here is an example demonstrating use cases of BelongsTo and HasOne.
class Player extends Model {}
Player.init({/* attributes */}, { sequelize, modelName: 'player' })
class Coach extends Model {}
Coach.init({/* attributes */}, { sequelize, modelName: 'coach' })
class Team extends Model {}
Team.init({/* attributes */}, { sequelize, modelName: 'team' });
Suppose our Player
model has information about its team as teamId
column. Information about each Team's Coach
is stored in the Team
model as coachId
column. These both scenarios requires different kind of 1:1 relation because foreign key relation is present on different models each time.
When information about association is present in source model we can use belongsTo
. In this case Player
is suitable for belongsTo
because it has teamId
column.
Player.belongsTo(Team) // `teamId` will be added on Player / Source model
When information about association is present in target model we can use hasOne
. In this case Coach
is suitable for hasOne
because Team
model store information about its Coach
as coachId
field.
Coach.hasOne(Team) // `coachId` will be added on Team / Target model
One-To-Many associations (hasMany)
One-To-Many associations are connecting one source with multiple targets. The targets however are again connected to exactly one specific source.
class User extends Model {}
User.init({/* ... */}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({/* ... */}, { sequelize, modelName: 'project' })
// OK. Now things get more complicated (not really visible to the user :)).
// First let's define a hasMany association
Project.hasMany(User, {as: 'Workers'})
This will add the attribute projectId
to User. Depending on your setting for underscored the column in the table will either be called projectId
or project_id
. Instances of Project will get the accessors getWorkers
and setWorkers
.
Sometimes you may need to associate records on different columns, you may use sourceKey
option:
class City extends Model {}
City.init({ countryCode: Sequelize.STRING }, { sequelize, modelName: 'city' });
class Country extends Model {}
Country.init({ isoCode: Sequelize.STRING }, { sequelize, modelName: 'country' });
// Here we can connect countries and cities base on country code
Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});
So far we dealt with a one-way association. But we want more! Let's define it the other way around by creating a many to many association in the next section.
Belongs-To-Many associations
Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.
Project.belongsToMany(User, {through: 'UserProject'});
User.belongsToMany(Project, {through: 'UserProject'});
This will create a new model called UserProject with the equivalent foreign keys projectId
and userId
. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).
Defining through
is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.
This will add methods getUsers
, setUsers
, addUser
,addUsers
to Project
, and getProjects
, setProjects
, addProject
, and addProjects
to User
.
Sometimes you may want to rename your models when using them in associations. Let's define users as workers and projects as tasks by using the alias (as
) option. We will also manually define the foreign keys to use:
User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId' })
Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId' })
foreignKey
will allow you to set source model key in the through relation.
otherKey
will allow you to set target model key in the through relation.
User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId', otherKey: 'projectId'})
Of course you can also define self references with belongsToMany:
Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
// This will create the table PersonChildren which stores the ids of the objects.
Source and target keys
If you want to create a belongs to many relationship that does not use the default primary key some setup work is required.
You must set the sourceKey
(optionally targetKey
) appropriately for the two ends of the belongs to many. Further you must also ensure you have appropriate indexes created on your relationships. For example:
const User = this.sequelize.define('User', {
id: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
field: 'user_id'
},
userSecondId: {
type: DataTypes.UUID,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
field: 'user_second_id'
}
}, {
tableName: 'tbl_user',
indexes: [
{
unique: true,
fields: ['user_second_id']
}
]
});
const Group = this.sequelize.define('Group', {
id: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
field: 'group_id'
},
groupSecondId: {
type: DataTypes.UUID,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
field: 'group_second_id'
}
}, {
tableName: 'tbl_group',
indexes: [
{
unique: true,
fields: ['group_second_id']
}
]
});
User.belongsToMany(Group, {
through: 'usergroups',
sourceKey: 'userSecondId'
});
Group.belongsToMany(User, {
through: 'usergroups',
sourceKey: 'groupSecondId'
});
If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:
class User extends Model {}
User.init({}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({}, { sequelize, modelName: 'project' })
class UserProjects extends Model {}
UserProjects.init({
status: DataTypes.STRING
}, { sequelize, modelName: 'userProjects' })
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
To add a new project to a user and set its status, you pass extra options.through
to the setter, which contains the attributes for the join table
user.addProject(project, { through: { status: 'started' }})
By default the code above will add projectId and userId to the UserProjects table, and remove any previously defined primary key attribute - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns. To enforce a primary key on the UserProjects
model you can add it manually.
class UserProjects extends Model {}
UserProjects.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
status: DataTypes.STRING
}, { sequelize, modelName: 'userProjects' })
With Belongs-To-Many you can query based on through relation and select specific attributes. For example using findAll
with through
User.findAll({
include: [{
model: Project,
through: {
attributes: ['createdAt', 'startedAt', 'finishedAt'],
where: {completed: true}
}
}]
});
Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using uniqueKey option.
Project.belongsToMany(User, { through: UserProjects, uniqueKey: 'my_custom_unique' })
Naming strategy
By default sequelize will use the model name (the name passed to sequelize.define
) to figure out the name of the model when used in associations. For example, a model named user
will add the functions get/set/add User
to instances of the associated model, and a property named .user
in eager loading, while a model named User
will add the same functions, but a property named .User
(notice the upper case U) in eager loading.
As we've already seen, you can alias models in associations using as
. In single associations (has one and belongs to), the alias should be singular, while for many associations (has many) it should be plural. Sequelize then uses the inflection library to convert the alias to its singular form. However, this might not always work for irregular or non-english words. In this case, you can provide both the plural and the singular form of the alias:
User.belongsToMany(Project, { as: { singular: 'task', plural: 'tasks' }})
// Notice that inflection has no problem singularizing tasks, this is just for illustrative purposes.
If you know that a model will always use the same alias in associations, you can provide it when creating the model
class Project extends Model {}
Project.init(attributes, {
name: {
singular: 'task',
plural: 'tasks',
},
sequelize,
modelName: 'project'
})
User.belongsToMany(Project);
This will add the functions add/set/get Tasks
to user instances.
Remember, that using as
to change the name of the association will also change the name of the foreign key. When using as
, it is safest to also specify the foreign key.
Invoice.belongsTo(Subscription)
Subscription.hasMany(Invoice)
Without as
, this adds subscriptionId
as expected. However, if you were to say Invoice.belongsTo(Subscription, { as: 'TheSubscription' })
, you will have both subscriptionId
and theSubscriptionId
, because sequelize is not smart enough to figure that the calls are two sides of the same relation. 'foreignKey' fixes this problem;
Invoice.belongsTo(Subscription, { as: 'TheSubscription', foreignKey: 'subscription_id' })
Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' })
Associating objects
Because Sequelize is doing a lot of magic, you have to call Sequelize.sync
after setting the associations! Doing so will allow you the following:
Project.hasMany(Task)
Task.belongsTo(Project)
Project.create()...
Task.create()...
Task.create()...
// save them... and then:
project.setTasks([task1, task2]).then(() => {
// saved!
})
// ok, now they are saved... how do I get them later on?
project.getTasks().then(associatedTasks => {
// associatedTasks is an array of tasks
})
// You can also pass filters to the getter method.
// They are equal to the options you can pass to a usual finder method.
project.getTasks({ where: 'id > 10' }).then(tasks => {
// tasks with an id greater than 10 :)
})
// You can also only retrieve certain fields of a associated object.
project.getTasks({attributes: ['title']}).then(tasks => {
// retrieve tasks with the attributes "title" and "id"
})
To remove created associations you can just call the set method without a specific id:
// remove the association with task1
project.setTasks([task2]).then(associatedTasks => {
// you will get task2 only
})
// remove 'em all
project.setTasks([]).then(associatedTasks => {
// you will get an empty array
})
// or remove 'em more directly
project.removeTask(task1).then(() => {
// it's gone
})
// and add 'em again
project.addTask(task1).then(() => {
// it's back again
})
You can of course also do it vice versa:
// project is associated with task1 and task2
task2.setProject(null).then(() => {
// and it's gone
})
For hasOne/belongsTo it's basically the same:
Task.hasOne(User, {as: "Author"})
Task.setAuthor(anAuthor)
Adding associations to a relation with a custom join table can be done in two ways (continuing with the associations defined in the previous chapter):
// Either by adding a property with the name of the join table model to the object, before creating the association
project.UserProjects = {
status: 'active'
}
u.addProject(project)
// Or by providing a second options.through argument when adding the association, containing the data that should go in the join table
u.addProject(project, { through: { status: 'active' }})
// When associating multiple objects, you can combine the two options above. In this case the second argument
// will be treated as a defaults object, that will be used if no data is provided
project1.UserProjects = {
status: 'inactive'
}
u.setProjects([project1, project2], { through: { status: 'active' }})
// The code above will record inactive for project one, and active for project two in the join table
When getting data on an association that has a custom join table, the data from the join table will be returned as a DAO instance:
u.getProjects().then(projects => {
const project = projects[0]
if (project.UserProjects.status === 'active') {
// .. do magic
// since this is a real DAO instance, you can save it directly after you are done doing magic
return project.UserProjects.save()
}
})
If you only need some of the attributes from the join table, you can provide an array with the attributes you want:
// This will select only name from the Projects table, and only status from the UserProjects table
user.getProjects({ attributes: ['name'], joinTableAttributes: ['status']})
Check associations
You can also check if an object is already associated with another one (N:M only). Here is how you'd do it:
// check if an object is one of associated ones:
Project.create({ /* */ }).then(project => {
return User.create({ /* */ }).then(user => {
return project.hasUser(user).then(result => {
// result would be false
return project.addUser(user).then(() => {
return project.hasUser(user).then(result => {
// result would be true
})
})
})
})
})
// check if all associated objects are as expected:
// let's assume we have already a project and two users
project.setUsers([user1, user2]).then(() => {
return project.hasUsers([user1]);
}).then(result => {
// result would be true
return project.hasUsers([user1, user2]);
}).then(result => {
// result would be true
})
Advanced Concepts
Scopes
This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see Scopes.
Association scopes allow you to place a scope (a set of default attributes for get
and create
) on the association. Scopes can be placed both on the associated model (the target of the association), and on the through table for n:m relations.
1:n
Assume we have models Comment, Post, and Image. A comment can be associated to either an image or a post via commentableId
and commentable
- we say that Post and Image are Commentable
class Post extends Model {}
Post.init({
title: Sequelize.STRING,
text: Sequelize.STRING
}, { sequelize, modelName: 'post' });
class Image extends Model {}
Image.init({
title: Sequelize.STRING,
link: Sequelize.STRING
}, { sequelize, modelName: 'image' });
class Comment extends Model {
getItem(options) {
return this[
'get' +
this.get('commentable')
[0]
.toUpperCase() +
this.get('commentable').substr(1)
](options);
}
}
Comment.init({
title: Sequelize.STRING,
commentable: Sequelize.STRING,
commentableId: Sequelize.INTEGER
}, { sequelize, modelName: 'comment' });
Post.hasMany(Comment, {
foreignKey: 'commentableId',
constraints: false,
scope: {
commentable: 'post'
}
});
Comment.belongsTo(Post, {
foreignKey: 'commentableId',
constraints: false,
as: 'post'
});
Image.hasMany(Comment, {
foreignKey: 'commentableId',
constraints: false,
scope: {
commentable: 'image'
}
});
Comment.belongsTo(Image, {
foreignKey: 'commentableId',
constraints: false,
as: 'image'
});
constraints: false
disables references constraints, as commentableId
column references several tables, we cannot add a REFERENCES
constraint to it.
Note that the Image -> Comment and Post -> Comment relations define a scope, commentable: 'image'
and commentable: 'post'
respectively. This scope is automatically applied when using the association functions:
image.getComments()
// SELECT "id", "title", "commentable", "commentableId", "createdAt", "updatedAt" FROM "comments" AS
// "comment" WHERE "comment"."commentable" = 'image' AND "comment"."commentableId" = 1;
image.createComment({
title: 'Awesome!'
})
// INSERT INTO "comments" ("id","title","commentable","commentableId","createdAt","updatedAt") VALUES
// (DEFAULT,'Awesome!','image',1,'2018-04-17 05:36:40.454 +00:00','2018-04-17 05:36:40.454 +00:00')
// RETURNING *;
image.addComment(comment);
// UPDATE "comments" SET "commentableId"=1,"commentable"='image',"updatedAt"='2018-04-17 05:38:43.948
// +00:00' WHERE "id" IN (1)
The getItem
utility function on Comment
completes the picture - it simply converts the commentable
string into a call to either getImage
or getPost
, providing an abstraction over whether a comment belongs to a post or an image. You can pass a normal options object as a parameter to getItem(options)
to specify any where conditions or includes.
n:m
Continuing with the idea of a polymorphic model, consider a tag table - an item can have multiple tags, and a tag can be related to several items.
For brevity, the example only shows a Post model, but in reality Tag would be related to several other models.
class ItemTag extends Model {}
ItemTag.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
tagId: {
type: Sequelize.INTEGER,
unique: 'item_tag_taggable'
},
taggable: {
type: Sequelize.STRING,
unique: 'item_tag_taggable'
},
taggableId: {
type: Sequelize.INTEGER,
unique: 'item_tag_taggable',
references: null
}
}, { sequelize, modelName: 'item_tag' });
class Tag extends Model {}
Tag.init({
name: Sequelize.STRING,
status: Sequelize.STRING
}, { sequelize, modelName: 'tag' });
Post.belongsToMany(Tag, {
through: {
model: ItemTag,
unique: false,
scope: {
taggable: 'post'
}
},
foreignKey: 'taggableId',
constraints: false
});
Tag.belongsToMany(Post, {
through: {
model: ItemTag,
unique: false
},
foreignKey: 'tagId',
constraints: false
});
Notice that the scoped column (taggable
) is now on the through model (ItemTag
).
We could also define a more restrictive association, for example, to get all pending tags for a post by applying a scope of both the through model (ItemTag
) and the target model (Tag
):
Post.belongsToMany(Tag, {
through: {
model: ItemTag,
unique: false,
scope: {
taggable: 'post'
}
},
scope: {
status: 'pending'
},
as: 'pendingTags',
foreignKey: 'taggableId',
constraints: false
});
post.getPendingTags();
SELECT
"tag"."id",
"tag"."name",
"tag"."status",
"tag"."createdAt",
"tag"."updatedAt",
"item_tag"."id" AS "item_tag.id",
"item_tag"."tagId" AS "item_tag.tagId",
"item_tag"."taggable" AS "item_tag.taggable",
"item_tag"."taggableId" AS "item_tag.taggableId",
"item_tag"."createdAt" AS "item_tag.createdAt",
"item_tag"."updatedAt" AS "item_tag.updatedAt"
FROM
"tags" AS "tag"
INNER JOIN "item_tags" AS "item_tag" ON "tag"."id" = "item_tag"."tagId"
AND "item_tag"."taggableId" = 1
AND "item_tag"."taggable" = 'post'
WHERE
("tag"."status" = 'pending');
constraints: false
disables references constraints on the taggableId
column. Because the column is polymorphic, we cannot say that it REFERENCES
a specific table.
Creating with associations
An instance can be created with nested association in one step, provided all elements are new.
BelongsTo / HasMany / HasOne association
Consider the following models:
class Product extends Model {}
Product.init({
title: Sequelize.STRING
}, { sequelize, modelName: 'product' });
class User extends Model {}
User.init({
firstName: Sequelize.STRING,
lastName: Sequelize.STRING
}, { sequelize, modelName: 'user' });
class Address extends Model {}
Address.init({
type: Sequelize.STRING,
line1: Sequelize.STRING,
line2: Sequelize.STRING,
city: Sequelize.STRING,
state: Sequelize.STRING,
zip: Sequelize.STRING,
}, { sequelize, modelName: 'address' });
Product.User = Product.belongsTo(User);
User.Addresses = User.hasMany(Address);
// Also works for `hasOne`
A new Product
, User
, and one or more Address
can be created in one step in the following way:
return Product.create({
title: 'Chair',
user: {
firstName: 'Mick',
lastName: 'Broadstone',
addresses: [{
type: 'home',
line1: '100 Main St.',
city: 'Austin',
state: 'TX',
zip: '78704'
}]
}
}, {
include: [{
association: Product.User,
include: [ User.Addresses ]
}]
});
Here, our user model is called user
, with a lowercase u - This means that the property in the object should also be user
. If the name given to sequelize.define
was User
, the key in the object should also be User
. Likewise for addresses
, except it's pluralized being a hasMany
association.
BelongsTo association with an alias
The previous example can be extended to support an association alias.
const Creator = Product.belongsTo(User, { as: 'creator' });
return Product.create({
title: 'Chair',
creator: {
firstName: 'Matt',
lastName: 'Hansen'
}
}, {
include: [ Creator ]
});
HasMany / BelongsToMany association
Let's introduce the ability to associate a product with many tags. Setting up the models could look like:
class Tag extends Model {}
Tag.init({
name: Sequelize.STRING
}, { sequelize, modelName: 'tag' });
Product.hasMany(Tag);
// Also works for `belongsToMany`.
Now we can create a product with multiple tags in the following way:
Product.create({
id: 1,
title: 'Chair',
tags: [
{ name: 'Alpha'},
{ name: 'Beta'}
]
}, {
include: [ Tag ]
})
And, we can modify this example to support an alias as well:
const Categories = Product.hasMany(Tag, { as: 'categories' });
Product.create({
id: 1,
title: 'Chair',
categories: [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' }
]
}, {
include: [{
association: Categories,
as: 'categories'
}]
})
Raw queries
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the function sequelize.query
.
By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").then(([results, metadata]) => {
// Results will be an empty array and metadata will contain the number of affected rows.
})
In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
.then(users => {
// We don't need spread here, since only the results will be returned for select queries
})
Several other query types are available. Peek into the source for details
A second option is the model. If you pass a model the returned data will be instances of that model.
// Callee is the model definition. This allows you to easily map a query to a predefined model
sequelize
.query('SELECT * FROM projects', {
model: Projects,
mapToModel: true // pass true here if you have any mapped fields
})
.then(projects => {
// Each record will now be an instance of Project
})
See more options in the query API reference. Some examples below:
sequelize.query('SELECT 1', {
// A function (or false) for logging your queries
// Will get called for every SQL query that gets sent
// to the server.
logging: console.log,
// If plain is true, then sequelize will only return the first
// record of the result set. In case of false it will return all records.
plain: false,
// Set this to true if you don't have a model definition for your query.
raw: false,
// The type of query you are executing. The query type affects how results are formatted before they are passed back.
type: Sequelize.QueryTypes.SELECT
})
// Note the second argument being null!
// Even if we declared a callee here, the raw: true would
// supersede and return a raw object.
sequelize
.query('SELECT * FROM projects', { raw: true })
.then(projects => {
console.log(projects)
})
"Dotted" attributes
If an attribute name of the table contains dots, the resulting objects will be nested. This is due to the usage of dottie.js under the hood. See below:
sequelize.query('select 1 as `foo.bar.baz`').then(rows => {
console.log(JSON.stringify(rows))
})
[{
"foo": {
"bar": {
"baz": 1
}
}
}]
Replacements
Replacements in a query can be done in two different ways, either using named parameters (starting with :
), or unnamed, represented by a ?
. Replacements are passed in the options object.
- If an array is passed,
?
will be replaced in the order that they appear in the array - If an object is passed,
:key
will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.
sequelize.query('SELECT * FROM projects WHERE status = ?',
{ replacements: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
sequelize.query('SELECT * FROM projects WHERE status = :status ',
{ replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.
sequelize.query('SELECT * FROM projects WHERE status IN(:status) ',
{ replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
To use the wildcard operator %, append it to your replacement. The following query matches users with names that start with 'ben'.
sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
{ replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
Bind Parameter
Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.
- If an array is passed,
$1
is bound to the 1st element in the array (bind[0]
) - If an object is passed,
$key
is bound toobject['key']
. Each key must begin with a non-numeric char.$1
is not a valid key, even ifobject['1']
exists. - In either case
$$
can be used to escape a literal$
sign.
The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.
The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may also be needed to typecast them, if the type cannot be inferred from the context $1::varchar
.
sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
{ bind: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
{ bind: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
Transactions
Sequelize supports two ways of using transactions:
- Managed, One which will automatically commit or rollback the transaction based on the result of a promise chain and, (if CLS enabled) pass the transaction to all calls within the callback
- Unmanaged, One which leaves committing, rolling back and passing the transaction to the user
The key difference is that the managed transaction uses a callback that expects a promise to be returned to it while the unmanaged transaction returns a promise.
Managed transaction (auto-callback)
Managed transactions handle committing or rolling back the transaction automatically. You start a managed transaction by passing a callback to sequelize.transaction
.
Notice how the callback passed to transaction
returns a promise chain, and does not explicitly call t.commit()
nor t.rollback()
. If all promises in the returned chain are resolved successfully the transaction is committed. If one or several of the promises are rejected, the transaction is rolled back.
return sequelize.transaction(t => {
// chain all your queries here. make sure you return them.
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(user => {
return user.setShooter({
firstName: 'John',
lastName: 'Boothe'
}, {transaction: t});
});
}).then(result => {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(err => {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
Throw errors to rollback
When using the managed transaction you should never commit or rollback the transaction manually. If all queries are successful, but you still want to rollback the transaction (for example because of a validation failure) you should throw an error to break and reject the chain:
return sequelize.transaction(t => {
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(user => {
// Woops, the query was successful but we still want to roll back!
throw new Error();
});
});
Automatically pass transactions to all queries
In the examples above, the transaction is still manually passed, by passing { transaction: t }
as the second argument. To automatically pass the transaction to all queries you must install the continuation local storage (CLS) module and instantiate a namespace in your own code:
const cls = require('continuation-local-storage');
const namespace = cls.createNamespace('my-very-own-namespace');
To enable CLS you must tell sequelize which namespace to use by using a static method of the sequelize constructor:
const Sequelize = require('sequelize');
Sequelize.useCLS(namespace);
new Sequelize(....);
Notice, that the useCLS()
method is on the constructor, not on an instance of sequelize. This means that all instances will share the same namespace, and that CLS is all-or-nothing - you cannot enable it only for some instances.
CLS works like a thread-local storage for callbacks. What this means in practice is that different callback chains can access local variables by using the CLS namespace. When CLS is enabled sequelize will set the transaction
property on the namespace when a new transaction is created. Since variables set within a callback chain are private to that chain several concurrent transactions can exist at the same time:
sequelize.transaction((t1) => {
namespace.get('transaction') === t1; // true
});
sequelize.transaction((t2) => {
namespace.get('transaction') === t2; // true
});
In most case you won't need to access namespace.get('transaction')
directly, since all queries will automatically look for a transaction on the namespace:
sequelize.transaction((t1) => {
// With CLS enabled, the user will be created inside the transaction
return User.create({ name: 'Alice' });
});
After you've used Sequelize.useCLS()
all promises returned from sequelize will be patched to maintain CLS context. CLS is a complicated subject - more details in the docs for cls-bluebird, the patch used to make bluebird promises work with CLS.
Note: _CLS only supports async/await, at the moment, when using cls-hooked package. Although, cls-hooked relies on experimental API async_hooks_
Concurrent/Partial transactions
You can have concurrent transactions within a sequence of queries or have some of them excluded from any transactions. Use the {transaction: }
option to control which transaction a query belong to:
Warning: SQLite does not support more than one transaction at the same time.
Without CLS enabled
sequelize.transaction((t1) => {
return sequelize.transaction((t2) => {
// With CLS enable, queries here will by default use t2
// Pass in the `transaction` option to define/alter the transaction they belong to.
return Promise.all([
User.create({ name: 'Bob' }, { transaction: null }),
User.create({ name: 'Mallory' }, { transaction: t1 }),
User.create({ name: 'John' }) // this would default to t2
]);
});
});
Isolation levels
The possible isolations levels to use when starting a transaction:
Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED // "READ UNCOMMITTED"
Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED // "READ COMMITTED"
Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ // "REPEATABLE READ"
Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE // "SERIALIZABLE"
By default, sequelize uses the isolation level of the database. If you want to use a different isolation level, pass in the desired level as the first argument:
return sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
}, (t) => {
// your transactions
});
The isolationLevel
can either be set globally when initializing the Sequelize instance or
locally for every transaction:
// globally
new Sequelize('db', 'user', 'pw', {
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});
// locally
sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});
Note: The SET ISOLATION LEVEL queries are not logged in case of MSSQL as the specified isolationLevel is passed directly to tedious
Unmanaged transaction (then-callback)
Unmanaged transactions force you to manually rollback or commit the transaction. If you don't do that, the transaction will hang until it times out. To start an unmanaged transaction, call sequelize.transaction()
without a callback (you can still pass an options object) and call then
on the returned promise. Notice that commit()
and rollback()
returns a promise.
return sequelize.transaction().then(t => {
return User.create({
firstName: 'Bart',
lastName: 'Simpson'
}, {transaction: t}).then(user => {
return user.addSibling({
firstName: 'Lisa',
lastName: 'Simpson'
}, {transaction: t});
}).then(() => {
return t.commit();
}).catch((err) => {
return t.rollback();
});
});
Usage with other sequelize methods
The transaction
option goes with most other options, which are usually the first argument of a method.
For methods that take values, like .create
, .update()
, etc. transaction
should be passed to the option in the second argument.
If unsure, refer to the API documentation for the method you are using to be sure of the signature.
After commit hook
A transaction
object allows tracking if and when it is committed.
An afterCommit
hook can be added to both managed and unmanaged transaction objects:
sequelize.transaction(t => {
t.afterCommit((transaction) => {
// Your logic
});
});
sequelize.transaction().then(t => {
t.afterCommit((transaction) => {
// Your logic
});
return t.commit();
})
The function passed to afterCommit
can optionally return a promise that will resolve before the promise chain
that created the transaction resolves
afterCommit
hooks are not raised if a transaction is rolled back
afterCommit
hooks do not modify the return value of the transaction, unlike standard hooks
You can use the afterCommit
hook in conjunction with model hooks to know when a instance is saved and available outside
of a transaction
model.afterSave((instance, options) => {
if (options.transaction) {
// Save done within a transaction, wait until transaction is committed to
// notify listeners the instance has been saved
options.transaction.afterCommit(() => /* Notify */)
return;
}
// Save done outside a transaction, safe for callers to fetch the updated model
// Notify
})
Locks
Queries within a transaction
can be performed with locks
return User.findAll({
limit: 1,
lock: true,
transaction: t1
})
Queries within a transaction can skip locked rows
return User.findAll({
limit: 1,
lock: true,
skipLocked: true,
transaction: t2
})
Scopes
Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders, where
, include
, limit
etc.
Definition
Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:
class Project extends Model {}
Project.init({
// Attributes
}, {
defaultScope: {
where: {
active: true
}
},
scopes: {
deleted: {
where: {
deleted: true
}
},
activeUsers: {
include: [
{ model: User, where: { active: true }}
]
},
random () {
return {
where: {
someNumber: Math.random()
}
}
},
accessLevel (value) {
return {
where: {
accessLevel: {
[Op.gte]: value
}
}
}
}
sequelize,
modelName: 'project'
}
});
You can also add scopes after a model has been defined by calling addScope
. This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.
The default scope is always applied. This means, that with the model definition above, Project.findAll()
will create the following query:
SELECT * FROM projects WHERE active = true
The default scope can be removed by calling .unscoped()
, .scope(null)
, or by invoking another scope:
Project.scope('deleted').findAll(); // Removes the default scope
SELECT * FROM projects WHERE deleted = true
It is also possible to include scoped models in a scope definition. This allows you to avoid duplicating include
, attributes
or where
definitions.
Using the above example, and invoking the active
scope on the included User model (rather than specifying the condition directly in that include object):
activeUsers: {
include: [
{ model: User.scope('active')}
]
}
Usage
Scopes are applied by calling .scope
on the model definition, passing the name of one or more scopes. .scope
returns a fully functional model instance with all the regular methods: .findAll
, .update
, .count
, .destroy
etc. You can save this model instance and reuse it later:
const DeletedProjects = Project.scope('deleted');
DeletedProjects.findAll();
// some time passes
// let's look for deleted projects again!
DeletedProjects.findAll();
Scopes apply to .find
, .findAll
, .count
, .update
, .increment
and .destroy
.
Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:
Project.scope('random', { method: ['accessLevel', 19]}).findAll();
SELECT * FROM projects WHERE someNumber = 42 AND accessLevel >= 19
Merging
Several scopes can be applied simultaneously by passing an array of scopes to .scope
, or by passing the scopes as consecutive arguments.
// These two are equivalent
Project.scope('deleted', 'activeUsers').findAll();
Project.scope(['deleted', 'activeUsers']).findAll();
SELECT * FROM projects
INNER JOIN users ON projects.userId = users.id
WHERE projects.deleted = true
AND users.active = true
If you want to apply another scope alongside the default scope, pass the key defaultScope
to .scope
:
Project.scope('defaultScope', 'deleted').findAll();
SELECT * FROM projects WHERE active = true AND deleted = true
When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similarly to Object.assign), except for where
and include
, which will be merged. Consider two scopes:
{
scope1: {
where: {
firstName: 'bob',
age: {
[Op.gt]: 20
}
},
limit: 2
},
scope2: {
where: {
age: {
[Op.gt]: 30
}
},
limit: 10
}
}
Calling .scope('scope1', 'scope2')
will yield the following query
WHERE firstName = 'bob' AND age > 30 LIMIT 10
Note how limit
and age
are overwritten by scope2
, while firstName
is preserved. The limit
, offset
, order
, paranoid
, lock
and raw
fields are overwritten, while where
is shallowly merged (meaning that identical keys will be overwritten). The merge strategy for include
will be discussed later on.
Note that attributes
keys of multiple applied scopes are merged in such a way that attributes.exclude
are always preserved. This allows merging several scopes and never leaking sensitive fields in final scope.
The same merge logic applies when passing a find object directly to findAll
(and similar finders) on a scoped model:
Project.scope('deleted').findAll({
where: {
firstName: 'john'
}
})
WHERE deleted = true AND firstName = 'john'
Here the deleted
scope is merged with the finder. If we were to pass where: { firstName: 'john', deleted: false }
to the finder, the deleted
scope would be overwritten.
Merging includes
Includes are merged recursively based on the models being included. This is a very powerful merge, added on v5, and is better understood with an example.
Consider four models: Foo, Bar, Baz and Qux, with has-many associations as follows:
class Foo extends Model {}
class Bar extends Model {}
class Baz extends Model {}
class Qux extends Model {}
Foo.init({ name: Sequelize.STRING }, { sequelize });
Bar.init({ name: Sequelize.STRING }, { sequelize });
Baz.init({ name: Sequelize.STRING }, { sequelize });
Qux.init({ name: Sequelize.STRING }, { sequelize });
Foo.hasMany(Bar, { foreignKey: 'fooId' });
Bar.hasMany(Baz, { foreignKey: 'barId' });
Baz.hasMany(Qux, { foreignKey: 'bazId' });
Now, consider the following four scopes defined on Foo:
{
includeEverything: {
include: {
model: this.Bar,
include: [{
model: this.Baz,
include: this.Qux
}]
}
},
limitedBars: {
include: [{
model: this.Bar,
limit: 2
}]
},
limitedBazs: {
include: [{
model: this.Bar,
include: [{
model: this.Baz,
limit: 2
}]
}]
},
excludeBazName: {
include: [{
model: this.Bar,
include: [{
model: this.Baz,
attributes: {
exclude: ['name']
}
}]
}]
}
}
These four scopes can be deeply merged easily, for example by calling Foo.scope('includeEverything', 'limitedBars', 'limitedBazs', 'excludeBazName').findAll()
, which would be entirely equivalent to calling the following:
Foo.findAll({
include: {
model: this.Bar,
limit: 2,
include: [{
model: this.Baz,
limit: 2,
attributes: {
exclude: ['name']
},
include: this.Qux
}]
}
});
Observe how the four scopes were merged into one. The includes of scopes are merged based on the model being included. If one scope includes model A and another includes model B, the merged result will include both models A and B. On the other hand, if both scopes include the same model A, but with different options (such as nested includes or other attributes), those will be merged recursively, as shown above.
The merge illustrated above works in the exact same way regardless of the order applied to the scopes. The order would only make a difference if a certain option was set by two different scopes - which is not the case of the above example, since each scope does a different thing.
This merge strategy also works in the exact same way with options passed to .findAll
, .findOne
and the like.
Associations
Sequelize has two different but related scope concepts in relation to associations. The difference is subtle but important:
- Association scopes Allow you to specify default attributes when getting and setting associations - useful when implementing polymorphic associations. This scope is only invoked on the association between the two models, when using the
get
,set
,add
andcreate
associated model functions - Scopes on associated models Allows you to apply default and other scopes when fetching associations, and allows you to pass a scoped model when creating associations. These scopes both apply to regular finds on the model and to find through the association.
As an example, consider the models Post and Comment. Comment is associated to several other models (Image, Video etc.) and the association between Comment and other models is polymorphic, which means that Comment stores a commentable
column, in addition to the foreign key commentable_id
.
The polymorphic association can be implemented with an association scope :
this.Post.hasMany(this.Comment, {
foreignKey: 'commentable_id',
scope: {
commentable: 'post'
}
});
When calling post.getComments()
, this will automatically add WHERE commentable = 'post'
. Similarly, when adding new comments to a post, commentable
will automagically be set to 'post'
. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see Association scopes
Consider then, that Post has a default scope which only shows active posts: where: { active: true }
. This scope lives on the associated model (Post), and not on the association like the commentable
scope did. Just like the default scope is applied when calling Post.findAll()
, it is also applied when calling User.getPosts()
- this will only return the active posts for that user.
To disable the default scope, pass scope: null
to the getter: User.getPosts({ scope: null })
. Similarly, if you want to apply other scopes, pass an array like you would to .scope
:
User.getPosts({ scope: ['scope1', 'scope2']});
If you want to create a shortcut method to a scope on an associated model, you can pass the scoped model to the association. Consider a shortcut to get all deleted posts for a user:
class Post extends Model {}
Post.init(attributes, {
defaultScope: {
where: {
active: true
}
},
scopes: {
deleted: {
where: {
deleted: true
}
}
},
sequelize,
});
User.hasMany(Post); // regular getPosts association
User.hasMany(Post.scope('deleted'), { as: 'deletedPosts' });
User.getPosts(); // WHERE active = true
User.getDeletedPosts(); // WHERE deleted = true
Read replication
Sequelize supports read replication, i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the write master, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is not handled by Sequelize, but should be set up by database backend).
const sequelize = new Sequelize('database', null, null, {
dialect: 'mysql',
port: 3306
replication: {
read: [
{ host: '8.8.8.8', username: 'read-username', password: 'some-password' },
{ host: '9.9.9.9', username: 'another-username', password: null }
],
write: { host: '1.1.1.1', username: 'write-username', password: 'any-password' }
},
pool: { // If you want to override the options used for the read/write pool you can do so here
max: 20,
idle: 30000
},
})
If you have any general settings that apply to all replicas you do not need to provide them for each instance. In the code above, database name and port is propagated to all replicas. The same will happen for user and password, if you leave them out for any of the replicas. Each replica has the following options:host
,port
,username
,password
,database
.
Sequelize uses a pool to manage connections to your replicas. Internally Sequelize will maintain two pools created using pool
configuration.
If you want to modify these, you can pass pool as an options when instantiating Sequelize, as shown above.
Each write
or useMaster: true
query will use write pool. For SELECT
read pool will be used. Read replica are switched using a basic round robin scheduling.
Migrations
Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.
You will need Sequelize CLI. The CLI ships support for migrations and project bootstrapping.
The CLI
Installing CLI
Let's start with installing CLI, you can find instructions here. Most preferred way is installing locally like this
$ npm install --save sequelize-cli
Bootstrapping
To create an empty project you will need to execute init
command
$ npx sequelize-cli init
This will create following folders
config
, contains config file, which tells CLI how to connect with databasemodels
, contains all models for your projectmigrations
, contains all migration filesseeders
, contains all seed files
Configuration
Before continuing further we will need to tell CLI how to connect to database. To do that let's open default config file config/config.json
. It looks something like this
{
"development": {
"username": "root",
"password": null,
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
Now edit this file and set correct database credentials and dialect. The keys of the objects(ex. "development") are used on model/index.js
for matching process.env.NODE_ENV
(When undefined, "development" is a default value.).
Note: If your database doesn't exists yet, you can just call db:create
command. With proper access it will create that database for you.
Creating first Model (and Migration)
Once you have properly configured CLI config file you are ready to create your first migration. It's as simple as executing a simple command.
We will use model:generate
command. This command requires two options
name
, Name of the modelattributes
, List of model attributes
Let's create a model named User
.
$ npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
This will do following
- Create a model file
user
inmodels
folder - Create a migration file with name like
XXXXXXXXXXXXXX-create-user.js
inmigrations
folder
Note: Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.
Running Migrations
Until this step, we haven't inserted anything into the database. We have just created required model and migration files for our first model User
. Now to actually create that table in database you need to run db:migrate
command.
$ npx sequelize-cli db:migrate
This command will execute these steps:
- Will ensure a table called
SequelizeMeta
in database. This table is used to record which migrations have run on the current database - Start looking for any migration files which haven't run yet. This is possible by checking
SequelizeMeta
table. In this case it will runXXXXXXXXXXXXXX-create-user.js
migration, which we created in last step. - Creates a table called
Users
with all columns as specified in its migration file.
Undoing Migrations
Now our table has been created and saved in database. With migration you can revert to old state by just running a command.
You can use db:migrate:undo
, this command will revert most recent migration.
$ npx sequelize-cli db:migrate:undo
You can revert back to initial state by undoing all migrations with db:migrate:undo:all
command. You can also revert back to a specific migration by passing its name in --to
option.
$ npx sequelize-cli db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js
Creating First Seed
Suppose we want to insert some data into a few tables by default. If we follow up on previous example we can consider creating a demo user for User
table.
To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.
Let's create a seed file which will add a demo user to our User
table.
$ npx sequelize-cli seed:generate --name demo-user
This command will create a seed file in seeders
folder. File name will look something like XXXXXXXXXXXXXX-demo-user.js
. It follows the same up / down
semantics as the migration files.
Now we should edit this file to insert demo user to User
table.
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Users', [{
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
createdAt: new Date(),
updatedAt: new Date()
}], {});
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('Users', null, {});
}
};
Running Seeds
In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple command.
$ npx sequelize-cli db:seed:all
This will execute that seed file and you will have a demo user inserted into User
table.
Note: Seeders execution is not stored anywhere unlike migrations, which use the SequelizeMeta
table. If you wish to override this please read Storage
section
Undoing Seeds
Seeders can be undone if they are using any storage. There are two commands available for that:
If you wish to undo most recent seed
$ npx sequelize-cli db:seed:undo
If you wish to undo a specific seed
$ npx sequelize-cli db:seed:undo --seed name-of-seed-as-in-data
If you wish to undo all seeds
$ npx sequelize-cli db:seed:undo:all
Advance Topics
Migration Skeleton
The following skeleton shows a typical migration file.
module.exports = {
up: (queryInterface, Sequelize) => {
// logic for transforming into the new state
},
down: (queryInterface, Sequelize) => {
// logic for reverting the changes
}
}
We can generate this file using migration:generate
. This will create xxx-migration-skeleton.js
in your migration folder.
$ npx sequelize-cli migration:generate --name migration-skeleton
The passed queryInterface
object can be used to modify the database. The Sequelize
object stores the available data types such as STRING
or INTEGER
. Function up
or down
should return a Promise
. Let's look at an example:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Person', {
name: Sequelize.STRING,
isBetaMember: {
type: Sequelize.BOOLEAN,
defaultValue: false,
allowNull: false
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Person');
}
}
The following is an example of a migration that performs two changes in the database, using a transaction to ensure that all instructions are successfully executed or rolled back in case of failure:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.sequelize.transaction((t) => {
return Promise.all([
queryInterface.addColumn('Person', 'petName', {
type: Sequelize.STRING
}, { transaction: t }),
queryInterface.addColumn('Person', 'favoriteColor', {
type: Sequelize.STRING,
}, { transaction: t })
])
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.sequelize.transaction((t) => {
return Promise.all([
queryInterface.removeColumn('Person', 'petName', { transaction: t }),
queryInterface.removeColumn('Person', 'favoriteColor', { transaction: t })
])
})
}
};
The next is an example of a migration that has a foreign key. You can use references to specify a foreign key:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Person', {
name: Sequelize.STRING,
isBetaMember: {
type: Sequelize.BOOLEAN,
defaultValue: false,
allowNull: false
},
userId: {
type: Sequelize.INTEGER,
references: {
model: {
tableName: 'users',
schema: 'schema'
}
key: 'id'
},
allowNull: false
},
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Person');
}
}
The next is an example of a migration that has uses async/await where you create an unique index on a new column:
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'Person',
'petName',
{
type: Sequelize.STRING,
},
{ transaction }
);
await queryInterface.addIndex(
'Person',
'petName',
{
fields: 'petName',
unique: true,
},
{ transaction }
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('Person', 'petName', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};
The .sequelizerc
File
This is a special configuration file. It lets you specify following options that you would usually pass as arguments to CLI:
env
: The environment to run the command inconfig
: The path to the config fileoptions-path
: The path to a JSON file with additional optionsmigrations-path
: The path to the migrations folderseeders-path
: The path to the seeders foldermodels-path
: The path to the models folderurl
: The database connection string to use. Alternative to using --config filesdebug
: When available show various debug information
Some scenarios where you can use it.
- You want to override default path to
migrations
,models
,seeders
orconfig
folder. - You want to rename
config.json
to something else likedatabase.json
And a whole lot more. Let's see how you can use this file for custom configuration.
For starters, let's create an empty file in the root directory of your project.
$ touch .sequelizerc
Now let's work with an example config.
const path = require('path');
module.exports = {
'config': path.resolve('config', 'database.json'),
'models-path': path.resolve('db', 'models'),
'seeders-path': path.resolve('db', 'seeders'),
'migrations-path': path.resolve('db', 'migrations')
}
With this config you are telling CLI to
- Use
config/database.json
file for config settings - Use
db/models
as models folder - Use
db/seeders
as seeders folder - Use
db/migrations
as migrations folder
Dynamic Configuration
Configuration file is by default a JSON file called config.json
. But sometimes you want to execute some code or access environment variables which is not possible in JSON files.
Sequelize CLI can read from both JSON
and JS
files. This can be setup with .sequelizerc
file. Let see how
First you need to create a .sequelizerc
file in the root folder of your project. This file should override config path to a JS
file. Like this
const path = require('path');
module.exports = {
'config': path.resolve('config', 'config.js')
}
Now Sequelize CLI will load config/config.js
for getting configuration options. Since this is a JS file you can have any code executed and export final dynamic configuration file.
An example of config/config.js
file
const fs = require('fs');
module.exports = {
development: {
username: 'database_dev',
password: 'database_dev',
database: 'database_dev',
host: '127.0.0.1',
dialect: 'mysql'
},
test: {
username: 'database_test',
password: null,
database: 'database_test',
host: '127.0.0.1',
dialect: 'mysql'
},
production: {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOSTNAME,
dialect: 'mysql',
dialectOptions: {
ssl: {
ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
}
}
}
};
Using Babel
Now you know how to use .sequelizerc
file. Now let's see how to use this file to use babel with sequelize-cli
setup. This will allow you to write migrations and seeders with ES6/ES7 syntax.
First install babel-register
$ npm i --save-dev babel-register
Now let's create .sequelizerc
file, it can include any configuration you may want to change for sequelize-cli
but in addition to that we want it to register babel for our codebase. Something like this
$ touch .sequelizerc # Create rc file
Now include babel-register
setup in this file
require("babel-register");
const path = require('path');
module.exports = {
'config': path.resolve('config', 'config.json'),
'models-path': path.resolve('models'),
'seeders-path': path.resolve('seeders'),
'migrations-path': path.resolve('migrations')
}
Now CLI will be able to run ES6/ES7 code from migrations/seeders etc. Please keep in mind this depends upon your configuration of .babelrc
. Please read more about that at babeljs.io.
Using Environment Variables
With CLI you can directly access the environment variables inside the config/config.js
. You can use .sequelizerc
to tell CLI to use config/config.js
for configuration. This is explained in last section.
Then you can just expose file with proper environment variables.
module.exports = {
development: {
username: 'database_dev',
password: 'database_dev',
database: 'database_dev',
host: '127.0.0.1',
dialect: 'mysql'
},
test: {
username: process.env.CI_DB_USERNAME,
password: process.env.CI_DB_PASSWORD,
database: process.env.CI_DB_NAME,
host: '127.0.0.1',
dialect: 'mysql'
},
production: {
username: process.env.PROD_DB_USERNAME,
password: process.env.PROD_DB_PASSWORD,
database: process.env.PROD_DB_NAME,
host: process.env.PROD_DB_HOSTNAME,
dialect: 'mysql'
}
};
Specifying Dialect Options
Sometime you want to specify a dialectOption, if it's a general config you can just add it in config/config.json
. Sometime you want to execute some code to get dialectOptions, you should use dynamic config file for those cases.
{
"production": {
"dialect":"mysql",
"dialectOptions": {
"bigNumberStrings": true
}
}
}
Production Usages
Some tips around using CLI and migration setup in production environment.
1) Use environment variables for config settings. This is better achieved with dynamic configuration. A sample production safe configuration may look like.
const fs = require('fs');
module.exports = {
development: {
username: 'database_dev',
password: 'database_dev',
database: 'database_dev',
host: '127.0.0.1',
dialect: 'mysql'
},
test: {
username: 'database_test',
password: null,
database: 'database_test',
host: '127.0.0.1',
dialect: 'mysql'
},
production: {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOSTNAME,
dialect: 'mysql',
dialectOptions: {
ssl: {
ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
}
}
}
};
Our goal is to use environment variables for various database secrets and not accidentally check them in to source control.
Storage
There are three types of storage that you can use: sequelize
, json
, and none
.
sequelize
: stores migrations and seeds in a table on the sequelize databasejson
: stores migrations and seeds on a json filenone
: does not store any migration/seed
Migration Storage
By default the CLI will create a table in your database called SequelizeMeta
containing an entry
for each executed migration. To change this behavior, there are three options you can add to the
configuration file. Using migrationStorage
, you can choose the type of storage to be used for
migrations. If you choose json
, you can specify the path of the file using migrationStoragePath
or the CLI will write to the file sequelize-meta.json
. If you want to keep the information in the
database, using sequelize
, but want to use a different table, you can change the table name using
migrationStorageTableName
. Also you can define a different schema for the SequelizeMeta
table by
providing the migrationStorageTableSchema
property.
{
"development": {
"username": "root",
"password": null,
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql",
// Use a different storage type. Default: sequelize
"migrationStorage": "json",
// Use a different file name. Default: sequelize-meta.json
"migrationStoragePath": "sequelizeMeta.json",
// Use a different table name. Default: SequelizeMeta
"migrationStorageTableName": "sequelize_meta",
// Use a different schema for the SequelizeMeta table
"migrationStorageTableSchema": "custom_schema"
}
}
Note: The none
storage is not recommended as a migration storage. If you decide to use it, be
aware of the implications of having no record of what migrations did or didn't run.
Seed Storage
By default the CLI will not save any seed that is executed. If you choose to change this behavior (!),
you can use seederStorage
in the configuration file to change the storage type. If you choose json
,
you can specify the path of the file using seederStoragePath
or the CLI will write to the file
sequelize-data.json
. If you want to keep the information in the database, using sequelize
, you can
specify the table name using seederStorageTableName
, or it will default to SequelizeData
.
{
"development": {
"username": "root",
"password": null,
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql",
// Use a different storage. Default: none
"seederStorage": "json",
// Use a different file name. Default: sequelize-data.json
"seederStoragePath": "sequelizeData.json",
// Use a different table name. Default: SequelizeData
"seederStorageTableName": "sequelize_data"
}
}
Configuration Connection String
As an alternative to the --config
option with configuration files defining your database, you can
use the --url
option to pass in a connection string. For example:
$ npx sequelize-cli db:migrate --url 'mysql://root:password@mysql_host.com/database_name'
Passing Dialect Specific Options
{
"production": {
"dialect":"postgres",
"dialectOptions": {
// dialect options like SSL etc here
}
}
}
Programmatic use
Sequelize has a sister library for programmatically handling execution and logging of migration tasks.
Query Interface
Using queryInterface
object described before you can change database schema. To see full list of public methods it supports check QueryInterface API
Resources
Addons & Plugins
ACL
Auto Code Generation & Scaffolding
- meteor modeler - Desktop tool for visual definition of Sequelize models and asssociations.
- sequelize-ui - Online tool for building models, relations and more.
- sequelizer - A GUI Desktop App for generating Sequelize models. Support for Mysql, Mariadb, Postgres, Sqlite, Mssql.
- sequelize-auto Generating models for SequelizeJS via the command line is another choice.
- pg-generator - Auto generate/scaffold Sequelize models for PostgreSQL database.
- sequelizejs-decorators decorators for composing sequelize models
Autoloader
- sequelize-autoload - An autoloader for Sequelize, inspired by PSR-0 and PSR-4.
Caching
Filters
- sequelize-transforms - Add configurable attribute transforms.
Fixtures / mock data
Hierarchies
- sequelize-hierarchy - Nested hierarchies for Sequelize.
Historical records / Time travel
- sequelize-temporal - Temporal tables (aka historical records)
Migrations
Slugification
- sequelize-slugify - Add slugs to sequelize models
Tokens
- sequelize-tokenify - Add unique tokens to sequelize models
Miscellaneous
- sequelize-deep-update - Update a sequelize instance and its included associated instances with new properties.
- sequelize-noupdate-attributes - Adds no update/readonly attributes support to models.
- sequelize-joi - Allows specifying Joi validation schema for JSONB model attributes in Sequelize.
TypeScript
Since v5, Sequelize provides its own TypeScript definitions. Please note that only TS >= 3.1 is supported.
As Sequelize heavily relies on runtime property assignments, TypeScript won't be very useful out of the box. A decent amount of manual type declarations are needed to make models workable.
Installation
In order to avoid installation bloat for non TS users, you must install the following typing packages manually:
@types/node
(this is universally required)@types/validator
@types/bluebird
Usage
Example of a minimal TypeScript project:
import { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';
import { HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';
class User extends Model {
public id!: number; // Note that the `null assertion` `!` is required in strict mode.
public name!: string;
public preferredName!: string | null; // for nullable fields
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
// Since TS cannot determine model association at compile time
// we have to declare them here purely virtually
// these will not exist until `Model.init` was called.
public getProjects!: HasManyGetAssociationsMixin<Project>; // Note the null assertions!
public addProject!: HasManyAddAssociationMixin<Project, number>;
public hasProject!: HasManyHasAssociationMixin<Project, number>;
public countProjects!: HasManyCountAssociationsMixin;
public createProject!: HasManyCreateAssociationMixin<Project>;
// You can also pre-declare possible inclusions, these will only be populated if you
// actively include a relation.
public readonly projects?: Project[]; // Note this is optional since it's only populated when explicitly requested in code
public static associations: {
projects: Association<User, Project>;
};
}
const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');
class Project extends Model {
public id!: number;
public ownerId!: number;
public name!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
class Address extends Model {
public userId!: number;
public address!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Project.init({
id: {
type: DataTypes.INTEGER.UNSIGNED, // you can omit the `new` but this is discouraged
autoIncrement: true,
primaryKey: true,
},
ownerId: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
}
}, {
sequelize,
tableName: 'projects',
});
User.init({
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
},
preferredName: {
type: new DataTypes.STRING(128),
allowNull: true
}
}, {
tableName: 'users',
sequelize: sequelize, // this bit is important
});
Address.init({
userId: {
type: DataTypes.INTEGER.UNSIGNED,
},
address: {
type: new DataTypes.STRING(128),
allowNull: false,
}
}, {
tableName: 'address',
sequelize: sequelize, // this bit is important
});
// Here we associate which actually populates out pre-declared `association` static and other methods.
User.hasMany(Project, {
sourceKey: 'id',
foreignKey: 'ownerId',
as: 'projects' // this determines the name in `associations`!
});
Address.belongsTo(User, {targetKey: 'id'});
User.hasOne(Address,{sourceKey: 'id'});
async function stuff() {
// Please note that when using async/await you lose the `bluebird` promise context
// and you fall back to native
const newUser = await User.create({
name: 'Johnny',
preferredName: 'John',
});
console.log(newUser.id, newUser.name, newUser.preferredName);
const project = await newUser.createProject({
name: 'first!',
});
const ourUser = await User.findByPk(1, {
include: [User.associations.projects],
rejectOnEmpty: true, // Specifying true here removes `null` from the return type!
});
console.log(ourUser.projects![0].name); // Note the `!` null assertion since TS can't know if we included
// the model or not
}
Usage of sequelize.define
TypeScript doesn't know how to generate a class
definition when we use the sequelize.define
method to define a Model. Therefore, we need to do some manual work and declare an interface and a type, and eventually cast the result of .define
to the static type.
// We need to declare an interface for our model that is basically what our class would be
interface MyModel extends Model {
readonly id: number;
}
// Need to declare the static model so `findOne` etc. use correct types.
type MyModelStatic = typeof Model & {
new (values?: object, options?: BuildOptions): MyModel;
}
// TS can't derive a proper class definition from a `.define` call, therefor we need to cast here.
const MyDefineModel = <MyModelStatic>sequelize.define('MyDefineModel', {
id: {
primaryKey: true,
type: DataTypes.INTEGER.UNSIGNED,
}
});
function stuffTwo() {
MyDefineModel.findByPk(1, {
rejectOnEmpty: true,
})
.then(myModel => {
console.log(myModel.id);
});
}
Upgrade to v5
Sequelize v5 is the next major release after v4
Breaking Changes
Support for Node 6 and up
Sequelize v5 will only support Node 6 and up #9015
Secure Operators
With v4 you started to get a deprecation warning String based operators are now deprecated
. Also concept of operators was introduced. These operators are Symbols which prevent hash injection attacks.
With v5
- Operators are now enabled by default.
- You can still use string operators by passing an operators map in
operatorsAliases
, but that will give you deprecation warning. - Op.$raw is removed
Typescript Support
Sequelize now ship official typings #10287. You can consider migrating away from external typings which may get out of sync.
Pooling
With v5 Sequelize now use sequelize-pool
which is a modernized fork of [email protected]
. You no longer need to call sequelize.close
to shutdown pool, this helps with lambda executions. #8468
Model
Validators
Custom validators defined per attribute (as opposed to the custom validators defined in the model's options) now run when the attribute's value is null
and allowNull
is true
(while previously they didn't run and the validation succeeded immediately). To avoid problems when upgrading, please check all your custom validators defined per attribute, where allowNull
is true
, and make sure all these validators behave correctly when the value is null
. See #9143.
Attributes
Model.attributes
now removed, use Model.rawAttributes
. #5320
Note: Please don't confuse this with options.attributes
, they are still valid
Paranoid Mode
With v5 if deletedAt
is set, record will be considered as deleted. paranoid
option will only use deletedAt
as flag. #8496
Model.bulkCreate
updateOnDuplicate
option which used to accept boolean and array, now only accepts non-empty array of attributes. #9288
Underscored Mode
Implementation of Model.options.underscored
is changed. You can find full specifications here.
Main outline
- Both
underscoredAll
andunderscored
options are merged into singleunderscored
option - All attributes are now generated with camelcase naming by default. With the
underscored
option set totrue
, thefield
option for attributes will be set as underscored version of attribute name. underscored
will control all attributes including timestamps, version and foreign keys. It will not affect any attribute which already specifies thefield
option.
Removed aliases
Many model based aliases has been removed #9372
Removed in v5 | Official Alternative |
---|---|
insertOrUpdate | upsert |
find | findOne |
findAndCount | findAndCountAll |
findOrInitialize | findOrBuild |
updateAttributes | update |
findById, findByPrimary | findByPk |
all | findAll |
hook | addHook |
Datatypes
Range
Now supports only one standard format [{ value: 1, inclusive: true }, { value: 20, inclusive: false }]
#9364
Case insensitive text
Added support for CITEXT
for Postgres and SQLite
Removed
NONE
type has been removed, use VIRTUAL
instead
Hooks
Removed aliases
Hooks aliases has been removed #9372
Removed in v5 | Official Alternative |
---|---|
[after,before]BulkDelete | [after,before]BulkDestroy |
[after,before]Delete | [after,before]Destroy |
beforeConnection | beforeConnect |
Sequelize
Removed aliases
Prototype references for many constants, objects and classes has been removed #9372
Removed in v5 | Official Alternative |
---|---|
Sequelize.prototype.Utils | Sequelize.Utils |
Sequelize.prototype.Promise | Sequelize.Promise |
Sequelize.prototype.TableHints | Sequelize.TableHints |
Sequelize.prototype.Op | Sequelize.Op |
Sequelize.prototype.Transaction | Sequelize.Transaction |
Sequelize.prototype.Model | Sequelize.Model |
Sequelize.prototype.Deferrable | Sequelize.Deferrable |
Sequelize.prototype.Error | Sequelize.Error |
Sequelize.prototype[error] | Sequelize[error] |
import Sequelize from 'sequelize';
const sequelize = new Sequelize('postgres://user:[email protected]:mydb');
/**
* In v4 you can do this
*/
console.log(sequelize.Op === Sequelize.Op) // logs `true`
console.log(sequelize.UniqueConstraintError === Sequelize.UniqueConstraintError) // logs `true`
Model.findAll({
where: {
[sequelize.Op.and]: [ // Using sequelize.Op or Sequelize.Op interchangeably
{
name: "Abc"
},
{
age: {
[Sequelize.Op.gte]: 18
}
}
]
}
}).catch(sequelize.ConnectionError, () => {
console.error('Something wrong with connection?');
});
/**
* In v5 aliases has been removed from Sequelize prototype
* You should use Sequelize directly to access Op, Errors etc
*/
Model.findAll({
where: {
[Sequelize.Op.and]: [ // Don't use sequelize.Op, use Sequelize.Op instead
{
name: "Abc"
},
{
age: {
[Sequelize.Op.gte]: 18
}
}
]
}
}).catch(Sequelize.ConnectionError, () => {
console.error('Something wrong with connection?');
});
Query Interface
changeColumn
no longer generates constraint with_idx
suffix. Now Sequelize does not specify any name for constraints thus defaulting to database engine naming. This aligns behavior ofsync
,createTable
andchangeColumn
.addIndex
aliases options aliases have been removed, use the following instead.indexName
=>name
indicesType
=>type
indexType
/method
=>using
Others
- Sequelize now use parameterized queries for all INSERT / UPDATE operations (except UPSERT). They provide better protection against SQL Injection attack.
ValidationErrorItem
now holds reference to original error in theoriginal
property, rather than the__raw
property.- retry-as-promised has been updated to
3.1.0
, which use any-promise. This module repeat allsequelize.query
operations. You can configureany-promise
to usebluebird
for better performance on Node 4 or 6 - Sequelize will throw for all
undefined
keys inwhere
options, In past versionsundefined
was converted tonull
.
Dialect Specific
MSSQL
- Sequelize now works with
tedious >= 6.0.0
. OlddialectOptions
has to be updated to match their new format. Please refer to tedious documentation. An example of newdialectOptions
is given below
dialectOptions: {
authentication: {
domain: 'my-domain'
},
options: {
requestTimeout: 60000,
cryptoCredentialsDetails: {
ciphers: "RC4-MD5"
}
}
}
MySQL
- Requires
mysql2 >= 1.5.2
for prepared statements
MariaDB
dialect: 'mariadb'
is now supported withmariadb
package
Packages
- removed: terraformer-wkt-parser #9545
- removed:
generic-pool
- added:
sequelize-pool
Changelog
5.0.0-beta.17
- fix(build): default null for multiple primary keys
- fix(util): improve performance of classToInvokable #10534
- fix(model/update): propagate paranoid to individualHooks query #10369
- fix(association): use minimal select for hasAssociation #10529
- fix(query-interface): reject with error for describeTable #10528
- fix(model): throw for invalid include type #10527
- fix(types): additional options for db.query and add missing retry #10512
- fix(query): don't prepare options & sql for every retry #10498
- feat: expose Sequelize.BaseError
- feat: upgrade to
[email protected]
#10494 - feat(sqlite/query-generator): support restart identity for truncate-table #10522
- feat(data-types): handle numbers passed as objects #10492
- feat(types): enabled string association #10481
- feat(postgres): allow customizing client_min_messages #10448
- refactor(data-types): move to classes #10495
- docs(legacy): fix N:M example #10509
- docs(migrations): use migrationStorageTableSchema #10417
- docs(hooks): add documentation for connection hooks #10410
- docs(addIndex): concurrently option #10409
- docs(model): fix typo #10405
- docs(usage): fix broken link on Basic Usage #10381
- docs(package.json): add homepage #10372
5.0.0-beta.16
- feat: add typescript typings #10287
- fix(mysql): match with newlines in error message #10320
- fix(update): skips update when nothing to update #10248
- fix(utils): flattenObject for null values #10293
- fix(instance-validator): don't skip custom validators on null #9143
- docs(transaction): after save example #10280
- docs(query-generator): typo #10277
- refactor(errors): restructure #10355
- refactor(scope): documentation #9087 #10312
- refactor: cleanup association and spread use #10276
5.0.0-beta.15
- fix(query-generator): fix addColumn create comment #10117
- fix(sync): throw when no models defined #10175
- fix(association): enable eager load with include all(#9928) #10173
- fix(sqlite): simplify connection error handling
- fix(model): prevent version number from being incremented as string #10217
- feat(dialect): mariadb #10192
- docs(migrations): improve dialect options docs
- docs: fix favicon #10242
- docs(model.init):
attribute.column.validate
option #10237 - docs(bulk-create): update support information about ignoreDuplicates
- docs: explain custom/new data types #10170
- docs(migrations): Simplify CLI Call #10201
- docs(migrations): added advanced skeleton example #10190
- docs(transaction): default isolation level #10111
- docs: typo in associations.md #10157
- refactor: reduce code complexity #10120
- refactor: optimize memoize use, misc cases #10122
- chore(lint): enforce consistent spacing #10193
5.0.0-beta.14
- fix(query): correctly quote identifier for attributes (#9964) #10118
- feat(postgres): dyanmic oids #10077
- fix(error): optimistic lock message #10068
- fix(package): update depd to version 2.0.0 #10081
- fix(model): validate virtual attribute (#9947) #10085
- fix(test): actually test get method with raw option #10059
- fix(model): return deep cloned value for toJSON #10058
- fix(model): create instance with many-to-many association with extra column (#10034) #10050
- fix(query-generator): fix bad property access #10056
- docs(upgrade-to-v4): typo #10060
- docs(model-usage): order expression format #10061
- chore(package): update retry-as-promised to version 3.1.0 #10065
- refactor(scopes): just in time options conforming #9735
- refactor: use sequelize-pool for pooling #10051
- refactor(*): cleanup code #10091
- refactor: use template strings #10055
- refactor(query-generation): cleanup template usage #10047
5.0.0-beta.13
- fix: throw on undefined where parameters #10048
- fix(model): improve wrong alias error message #10041
- feat(sqlite): CITEXT datatype #10036
- fix(postgres): remove if not exists and cascade from create/drop database queries #10033
- fix(syntax): correct parentheses around union #10003
- feat(query-interface): createDatabase / dropDatabase support #10027
- feat(postgres): CITEXT datatype #10024
- feat: pass uri query parameters to dialectOptions #10025
- docs(query-generator): remove doc about where raw query #10017
- fix(query): handle undefined field on unique constraint error #10018
- fix(model): sum returns zero when empty matching #9984
- feat(query-generator): add startsWith, endsWith and substring operators #9999
- docs(sequelize): correct jsdoc annotations for authenticate #10002
- docs(query-interface): add bulkUpdate docs #10005
- fix(tinyint): ignore params for TINYINT on postgres #9992
- fix(belongs-to): create now returns target model #9980
- refactor(model): remove .all alias #9975
- perf: fix memory leak due to instance reference by isImmutable #9973
- feat(sequelize): dialectModule option #9972
- fix(query): check valid warn message #9948
- fix(model): check for own property when overriding association mixins #9953
- fix(create-table): support for uniqueKeys #9946
- refactor(transaction): remove autocommit mode #9921
- feat(sequelize): getDatabaseName #9937
- refactor: remove aliases #9933
- feat(belongsToMany): override unique constraint name with uniqueKey #9914
- fix(postgres): properly disconnect connections #9911
- docs(instances.md): add section for restore() #9917
- docs(hooks.md): add warning about memory limits of individual hooks #9881
- fix(package): update debug to version 4.0.0 #9908
- feat(postgres): support ignoreDuplicates with ON CONFLICT DO NOTHING #9883
5.0.0-beta.12
- fix(changeColumn): normalize attribute #9897
- feat(describeTable): support string length for mssql #9896
- feat(describeTable): support autoIncrement for mysql #9894
- fix(sqlite): unable to reference foreignKey on primaryKey #9893
- fix(postgres): enum with string COMMENT breaks query #9891
- fix(changeColumn): use engine defaults for foreign/unique key naming #9890
- fix(transaction): fixed unhandled rejection when connection acquire timeout #9879
- fix(sqlite): close connection properly and cleanup files #9851
- fix(model): incorrect error message for findCreateFind #9849
5.0.0-beta.11
- fix(count): duplicate mapping of fields break scopes #9788
- fix(model): bulkCreate should populate dataValues directly #9797
- fix(mysql): improve unique key violation handling #9724
- fix(separate): don't propagate group to separated queries #9754
- fix(scope): incorrect query generated when sequelize.fn used with scopes #9730
- fix(json): access included data with attributes #9662
- (fix): pass offset in UNION'ed queries #9577
- fix(destroy): attributes updated in a beforeDestroy hook are now persisted on soft delete #9319
- fix(addScope): only throw when defaultScope is defined #9703
5.0.0-beta.10
- fix(belongsToMany): association.add returns array of array of through records #9700
- feat: association hooks #9590
- fix(bulkCreate): dont map dataValue to fields for individualHooks:true#9672
- feat(postgres): drop enum support #9641
- feat(validation): improve validation for type#9660
- feat: allow querying sqlite_master table #9645
- fix(hasOne.sourceKey): setup sourceKeyAttribute for joins #9658
- fix: throw when type of array values is not defined #9649
- fix(query-generator): ignore undefined keys in query #9548
- fix(model): unable to override rejectOnEmpty #9632
- fix(reload): instance.changed() remains unaffected #9615
- feat(model): column level comments #9573
- docs: cleanup / correct jsdoc references #9702
5.0.0-beta.9
- fix(model): ignore undefined values in update payload #9587
- fix(mssql): set encrypt as default false for dialect options #9588
- fix(model): ignore VIRTUAL/getters with attributes.exclude #9568
- feat(data-types): CIDR, INET, MACADDR support for Postgres #9567
- fix: customize allowNull message with notNull validator #9549
5.0.0-beta.8
- feat(query-generator): Generate INSERT / UPDATE using bind parameters #9431 #9492
- performance: remove terraformer-wkt-parser dependency #9545
- fix(constructor): set username, password, database via options in addition to connection string#9517
- fix(associations/belongs-to-many): catch EmptyResultError in set/add helpers #9535
- fix: sync with alter:true doesn't use field name #9529
- fix(UnknownConstraintError): improper handling of error options #9547
5.0.0-beta.7
- fix(data-types/blob): only return null for mysql binary null #9441
- fix(errors): use standard .original rather than .__raw for actual error
- fix(connection-manager): mssql datatype parsing #9470
- fix(query/removeConstraint): support schemas
- fix: use Buffer.from
- fix(transactions): return patched promise from sequelize.query #9473
5.0.0-beta.6
- fix(postgres/query-generator): syntax error with auto-increment SMALLINT #9406
- fix(postgres/range): inclusive property lost in JSON format #8471
- fix(postgres/range): range bound not applied #8176
- fix(mssql): no unique constraint error thrown for PRIMARY case #9415
- fix(query-generator): regexp operator escaping
- docs: various improvements and hinting update
5.0.0-beta.5
- fix: inject foreignKey when using separate:true #9396
- fix(isSoftDeleted): just use deletedAt as flag
- feat(hasOne): sourceKey support with key validation #9382
- fix(query-generator/deleteQuery): remove auto limit #9377
- feat(postgres): skip locked support #9197
- fix(mssql): case sensitive operation fails because of uppercased system table references #9337
5.0.0-beta.4
- change(model): setDataValue should not mark null to null as changed #9347
- change(mysql/connection-manager): do not execute SET time_zone query if keepDefaultTimezone config is true #9358
- feat(transactions): Add afterCommit hooks for transactions #9287
5.0.0-beta.3
- change(model): new options.underscored implementation #9304
- fix(mssql): duplicate order generated with limit offset #9307
- fix(scope): do not assign scope on eagerly loaded associations #9292
- change(bulkCreate): only support non-empty array as updateOnDuplicate
5.0.0-beta.2
- change(operators): Symbol operators now enabled by default, removed deprecation warning
- fix(model): don't add LIMIT in findOne() queries on unique key #9248
- fix(model): use schema when generating foreign keys #9029
5.0.0-beta.1
- fix(postgres): reserved words support #9236
- fix(findOrCreate): warn and handle unknown attributes in defaults
- fix(query-generator): 1-to-many join in subQuery filter missing where clause #9228
5.0.0-beta
Working with legacy tables
While out of the box Sequelize will seem a bit opinionated it's easy to work legacy tables and forward proof your application by defining (otherwise generated) table and field names.
Tables
class User extends Model {}
User.init({
// ...
}, {
modelName: 'user',
tableName: 'users',
sequelize,
});
Fields
class MyModel extends Model {}
MyModel.init({
userId: {
type: Sequelize.INTEGER,
field: 'user_id'
}
}, { sequelize });
Primary keys
Sequelize will assume your table has a id
primary key property by default.
To define your own primary key:
class Collection extends Model {}
Collection.init({
uid: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true // Automatically gets converted to SERIAL for postgres
}
}, { sequelize });
class Collection extends Model {}
Collection.init({
uuid: {
type: Sequelize.UUID,
primaryKey: true
}
}, { sequelize });
And if your model has no primary key at all you can use Model.removeAttribute('id');
Foreign keys
// 1:1
Organization.belongsTo(User, { foreignKey: 'owner_id' });
User.hasOne(Organization, { foreignKey: 'owner_id' });
// 1:M
Project.hasMany(Task, { foreignKey: 'tasks_pk' });
Task.belongsTo(Project, { foreignKey: 'tasks_pk' });
// N:M
User.belongsToMany(Role, { through: 'user_has_roles', foreignKey: 'user_role_user_id' });
Role.belongsToMany(User, { through: 'user_has_roles', foreignKey: 'roles_identifier' });
Who's using sequelize?
... we are avid users of sequelize (and have been for the past 18 months) (Feb 2017)
We've been using sequelize since we started in the beginning of 2015. We use it for our graphql servers (in connection with graphql-sequelize), and for all our background workers.
We have used Sequelize in enterprise projects for some of our Fortune 100 and Fortune 500 clients. It is used in deployments that are depended on by hundreds of millions of devices every year.
Using Sequelize in production for two different apps with 30k+ daily users by 2 years. I doubt there is something better at this moment in terms of productivity and features.
Legal Notice
License
Sequelize library is distributed with MIT license. You can find original license here.
MIT License
Copyright (c) 2014-present Sequelize contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
AUTHOR(S)
Main author:
Sascha Depold
Uhlandstr. 160
10719 Berlin
sascha [at] depold [dot] com
[plus] 49 152 [slash] 03878582
INHALTLICHE VERANTWORTUNG
Ich übernehme keine Haftung für ausgehende Links.
Daher musst du dich bei Problemen an deren Betreiber wenden!