How to use Sequelize in Node.js ?

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication and many more.

Features of Sequelize:

  • Sequelize is a third-party package to be precise its an Object-Relational Mapping Library(ORM)..
  • Standardization ORMs usually have a single schema definition in the code. This makes it very clear what the schema is, and very simple to change it.
  • No need to learn SQL – queries are written in plain JavaScript.

Setting up a Node.js app:

  • Start Node.js app using the following command:
    npm init -y

Installation of Sequelize:

  1. Sequelize needs MySql module installed in your project. if you have not installed MySql module then make sure before installing Sequelize you need to install MySql2 module. You need to install this module by using the following command.
    npm install mysql2
  2. After installing the MySql2 module, we have to install Sequelize module to install this module by using the following command.
    npm install sequelize

Requiring module:

  • You need to include Sequelize module in your project by using these lines.
    const Sequelize = require('sequelize');

Configuring database.js file:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Include Sequelize module
const Sequelize = require('sequelize')
  
// Creating new Object of Sequelize
const sequelize = new Sequelize(
    'DATABASE_NAME',
    'DATABASE_USER_NAME',
    'DATABASE_PASSWORD', {
  
        // Explicitly specifying 
        // mysql database
        dialect: 'mysql',
  
        // By default host is 'localhost'           
        host: 'localhost'
    }
);
  
// Exporting the sequelize object. 
// We can use it in another file
// for creating models
module.exports = sequelize

chevron_right


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.