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.
Here we explaining an example of a Database connection with MySQL using Squeeze.
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. So there is no need to learn SOL.
Setting up a Node.js app:
Start Node.js app using the following command:
// initialise npm
npm init
Installation of Required packages:
Sequelize needs the 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.
// install mysql2
npm install mysql2
After installing the MySql2 module, we have to install Sequelize module to install this module by using the following command.
// install sequelize
npm install sequelize
Requiring module:
For including sequelize in our application we have to add these few lines
// include sequelize
const sequelize = require('sequelize');
For this application, we are creating two files
index.js
databaseConnection.js
databaseConnection.js : explain data onnection using sequelize
//include sequelize
const sequelize = require('sequelize');
// create new object for Database connection
const Sequelize = new sequelize(
'sequelize_database_db',
'root',
'root',
{
host: "localhost",
dialect: "mysql"
})
// export module
module.exports = Sequelize;
index.js : calling database connection script and run application
// import database connection module
const Sequelize = require('./databaseConnection');
// sequelize db Connection ...
Sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
Run application : Open terminal and run command
// Run app
node index.js
OutPut: