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:

  1. const Sequelize = require('sequelize');
  2. // Option 1: Passing parameters separately
  3. const sequelize = new Sequelize('database', 'username', 'password', {
  4. host: 'localhost',
  5. dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
  6. });
  7. // Option 2: Passing a connection URI
  8. const sequelize = new Sequelize('postgres://user:pass@example.com: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:

  1. const sequelize = new Sequelize({
  2. dialect: 'sqlite',
  3. storage: 'path/to/database.sqlite'
  4. });

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:

  1. const sequelize = new Sequelize(/* ... */, {
  2. // ...
  3. pool: {
  4. max: 5,
  5. min: 0,
  6. acquire: 30000,
  7. idle: 10000
  8. }
  9. });

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:

  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. });

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