Getting started

Installation

Sequelize is available via NPM and Yarn.

  1. // Using NPM
  2. $ npm install --save sequelize
  3. # And one of the following:
  4. $ npm install --save pg pg-hstore
  5. $ npm install --save mysql2
  6. $ npm install --save sqlite3
  7. $ npm install --save tedious // MSSQL
  8. // Using Yarn
  9. $ yarn add sequelize
  10. # And one of the following:
  11. $ yarn add pg pg-hstore
  12. $ yarn add mysql2
  13. $ yarn add sqlite3
  14. $ yarn add tedious // MSSQL

Setting up a connection

Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database if you're connecting to the DB from a single process. If you're connecting to the DB from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of "max connection pool size divided by number of instances". So, if you wanted a max connection pool size of 90 and you had 3 worker processes, each process's instance should have a max connection pool size of 30.

  1. const Sequelize = require('sequelize');
  2. const sequelize = new Sequelize('database', 'username', 'password', {
  3. host: 'localhost',
  4. dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
  5. operatorsAliases: false,
  6. pool: {
  7. max: 5,
  8. min: 0,
  9. acquire: 30000,
  10. idle: 10000
  11. },
  12. // SQLite only
  13. storage: 'path/to/database.sqlite'
  14. });
  15. // Or you can simply use a connection uri
  16. const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');

The Sequelize constructor takes a whole slew of options that are available via the API reference.

Test the connection

You can use the .authenticate() function like this to test the connection.

  1. sequelize
  2. .authenticate()
  3. .then(() => {
  4. console.log('Connection has been established successfully.');
  5. })
  6. .catch(err => {
  7. console.error('Unable to connect to the database:', err);
  8. });

Your first model

Models are defined with sequelize.define('name', {attributes}, {options}).

  1. const User = sequelize.define('user', {
  2. firstName: {
  3. type: Sequelize.STRING
  4. },
  5. lastName: {
  6. type: Sequelize.STRING
  7. }
  8. });
  9. // force: true will drop the table if it already exists
  10. User.sync({force: true}).then(() => {
  11. // Table created
  12. return User.create({
  13. firstName: 'John',
  14. lastName: 'Hancock'
  15. });
  16. });

You can read more about creating models at Model API reference

Your first query

  1. User.findAll().then(users => {
  2. console.log(users)
  3. })

You can read more about finder functions on models like .findAll() at Data retrieval or how to do specific queries like WHERE and JSONB at Querying.

Application wide model options

The Sequelize constructor takes a define option which will be used as the default options for all defined models.

  1. const sequelize = new Sequelize('connectionUri', {
  2. define: {
  3. timestamps: false // true by default
  4. }
  5. });
  6. const User = sequelize.define('user', {}); // timestamps is false by default
  7. const Post = sequelize.define('post', {}, {
  8. timestamps: true // timestamps will now be true
  9. });

Promises

Sequelize uses Bluebird promises to control async control-flow.

Note:Sequelize use independent copy of Bluebird instance. You can access it using Sequelize.Promise if you want to set any Bluebird specific options

If you are unfamiliar with how promises work, don't worry, you can read up on them here.

Basically, a promise represents a value which will be present at some point - "I promise you I will give you a result or an error at some point". This means that

  1. // DON'T DO THIS
  2. user = User.findOne()
  3. console.log(user.get('firstName'));

will never work! This is because user is a promise object, not a data row from the DB. The right way to do it is:

  1. User.findOne().then(user => {
  2. console.log(user.get('firstName'));
  3. });

When your environment or transpiler supports async/await this will work but only in the body of an async function:

  1. user = await User.findOne()
  2. console.log(user.get('firstName'));

Once you've got the hang of what promises are and how they work, use the bluebird API reference as your go-to tool. In particular, you'll probably be using .all a lot.