,

How to Establish a Connection with Sequelize in Express JS

Posted by






Setting up Sequelize Connection with Express JS

Setting up Sequelize Connection with Express JS

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. Express JS, on the other hand, is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

To set up the connection between Sequelize and Express JS, follow these steps:

  1. Install Sequelize and Sequelize CLI if you haven’t already:
  2. npm install sequelize sequelize-cli
  3. Install the database driver for your chosen database (e.g. npm install pg for PostgreSQL).
  4. Create a new directory for your project and navigate into it.
  5. Initialize a new Node.js project and install Express:
  6. npm init -y
    npm install express
  7. Initialize Sequelize in your project:
  8. npx sequelize-cli init
  9. Create a database and configure the connection in config/config.js:
  10. module.exports = {
      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'
      }
    };
  11. Create a Sequelize model and migrate it:
  12. npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
    npx sequelize-cli db:migrate
  13. Create a new Express app and set up the Sequelize connection in app.js:
  14. const express = require('express');
    const app = express();
    const { Sequelize, DataTypes } = require('sequelize');
    
    const sequelize = new Sequelize('database_development', 'root', null, {
      host: 'localhost',
      dialect: 'mysql'
    });
    
    // Test the connection
    (async () => {
      try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');
      } catch (error) {
        console.error('Unable to connect to the database:', error);
      }
    })();
    
    app.listen(3000, () => {
      console.log('App listening on port 3000');
    });

With these steps, you should now have a working connection between Sequelize and Express JS in your project. You can now start building your application and interacting with the database using Sequelize’s powerful features.