Introduction to Sequelize in NodeJS


Sequelize follows a promise-based Node.js ORM structure for different databases like – Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. Sequelize have multiple features which makes it easy to implement and use.

Some of the main features of sequelize are as follows −

  • Sequelize is a third-party package.

  • It uses an Object-Relational Mapping to map objects. That's why its called an ORM.

  • Sequelize supports solid transaction support along with eager and lazy loading concept.

  • It can also perform read replication on databases.

  • Sequelize follows standardization, which means it has a single schema definition in the code. Standardization makes the schema easy to read and understand along with making changes.

  • In sequelize, the queries are written in plain Javascript. Therefore, you don't need to learn SQL.

Installing Sequelize

  • Before installing sequelize, please check if the Node.js server is properly initialized on the system using the following command.

>> npm init -y
  • The MySQL dependency needs to be installed for sequelize. For Sequelize, you need to install mysql2 as it does not works on myql. Therefore install the mysql dependency by using the following command −

>> npm install mysql2
  • After installing MySQL, we will now install Sequelize by using the following command −

>> npm install sequelize

You need to add the following statement in every project to include sequelize.

const Sequelize = require('sequelize');

Configuring database.js file for Connection

// Including the Sequelize module
const Sequelize = require('sequelize')

// Creating a sequelize object for DB connection
const sequelize = new Sequelize(
   'YOUR_DB_NAME',
   'YOUR_DB_USER_NAME',
   'YOUR_DB_PASSWORD', {

      dialect: 'mysql',
      // Defining the default host
      host: 'localhost'
   }
);

// Exporting the sequelize object.
// To use it in other files as well.
module.exports = sequelize

Updated on: 27-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements