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:
- Install Sequelize and Sequelize CLI if you haven’t already:
- Install the database driver for your chosen database (e.g.
npm install pg
for PostgreSQL). - Create a new directory for your project and navigate into it.
- Initialize a new Node.js project and install Express:
- Initialize Sequelize in your project:
- Create a database and configure the connection in
config/config.js
: - Create a Sequelize model and migrate it:
- Create a new Express app and set up the Sequelize connection in
app.js
:
npm install sequelize sequelize-cli
npm init -y
npm install express
npx sequelize-cli init
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'
}
};
npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
npx sequelize-cli db:migrate
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.