Sequelize is a powerful and widely-used Object-Relational Mapping (ORM) library for Node.js that supports various SQL databases, including MySQL, PostgreSQL, SQLite, and MariaDB. It provides an abstraction layer over SQL queries, allowing developers to interact with their database using JavaScript instead of writing raw SQL queries. This makes it easier to manage and manipulate data, especially when working with complex data models.
Sequelize is an ORM that helps in managing databases by abstracting complex SQL queries into JavaScript functions. It supports various relational databases and provides features like data validation, associations, and query building.
To start using Sequelize with Express.js, you need to install the required packages.
npm install express sequelize sequelize-cli mysql2
express
: The Express.js framework.sequelize
: The Sequelize ORM library.sequelize-cli
: Command-line interface for Sequelize, useful for generating models, migrations, and more.mysql2
: A MySQL client for Node.js, required for connecting to a MySQL database.Sequelize provides a command-line tool to initialize the project structure.
npx sequelize-cli init
This command will create the following structure:
config/
: Configuration files for different environments (development, production).models/
: This folder contains all the database models (tables).migrations/
: Migrations are used to modify the database schema over time.seeders/
: Seed files are used to populate the database with initial data.After initializing Sequelize, you need to configure the database connection.
config/config.json
{
"development": {
"username": "root",
"password": "password",
"database": "mydatabase",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": "password",
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": "password",
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
username
: The database username.password
: The database password.database
: The database name.host
: The database host.dialect
: The type of SQL database (e.g., mysql
, postgres
, sqlite
).In Sequelize, a model represents a table in the database. Each model is a JavaScript class that defines the structure of the table, including its columns and data types.
You can create a model using Sequelize’s command-line tool.
npx sequelize-cli model:generate --name User --attributes name:string,email:string,age:integer
This command generates a model file in the models/
directory and a migration file in the migrations/
directory.
models/user.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
// define association here
}
}
User.init({
name: DataTypes.STRING,
email: DataTypes.STRING,
age: DataTypes.INTEGER
}, {
sequelize,
modelName: 'User',
});
return User;
};
Migrations are used to apply changes to the database schema, such as creating or altering tables.
npx sequelize-cli db:migrate
This command will create the Users
table in the database with the columns name
, email
, and age
.
To create a new record in the database, you can use the create()
method provided by Sequelize.
app.js
const express = require('express');
const { User } = require('./models');
const app = express();
app.use(express.json());
app.post('/users', async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Users
table using the data provided in the request body.{ name: 'John', email: 'john@example.com', age: 25 }
)./users
with the user data, a new record is inserted into the Users
table, and the created user is returned in the response.To read data from the database, you can use the findAll()
and findOne()
methods.
app.js
(continued)
app.get('/users', async (req, res) => {
try {
const users = await User.findAll();
res.json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/users/:id', async (req, res) => {
try {
const user = await User.findOne({ where: { id: req.params.id } });
if (user) {
res.json(user);
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Users
table.id
)./users
, all users in the Users
table are returned./users/:id
, the user with the specified ID is returned, or a 404 error is returned if the user does not exist.To update an existing record, you can use the update()
method.
app.js
(continued)
app.put('/users/:id', async (req, res) => {
try {
const [updated] = await User.update(req.body, {
where: { id: req.params.id }
});
if (updated) {
const updatedUser = await User.findOne({ where: { id: req.params.id } });
res.json(updatedUser);
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
id
using the data provided in the request body./users/:id
with the updated data, the specified user record is updated, and the updated user is returned in the response.To delete a record from the database, you can use the destroy()
method.
app.js
(continued)
app.delete('/users/:id', async (req, res) => {
try {
const deleted = await User.destroy({
where: { id: req.params.id }
});
if (deleted) {
res.json({ message: 'User deleted' });
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
id
./users/:id
, the specified user record is deleted, and a confirmation message is returned in the response.Sequelize allows you to define associations (relationships) between different models, such as one-to-many
, many-to-many
, and one-to-one
relationships.
Example: Let’s create a Post
model that has a belongsTo
relationship with the User
model.
models/post.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Post extends Model {
static associate(models) {
Post.belongsTo(models.User, { foreignKey: 'userId' });
}
}
Post.init({
title: DataTypes.STRING,
content: DataTypes.TEXT,
userId: DataTypes.INTEGER
}, {
sequelize,
modelName: 'Post',
});
return Post;
};
belongsTo
relationship between Post
and User
. Each post belongs to a single user.You can use associations to retrieve related data. For example, you can fetch a user along with their posts.
app.js
(continued)
app.get('/users/:id/posts', async (req, res) => {
try {
const user = await User.findOne({
where: { id: req.params.id },
include: Post
});
if (user) {
res.json(user);
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
/users/:id/posts
, the user and their associated posts are returned.Sequelize is a powerful ORM that simplifies database interactions in Express.js applications. By using Sequelize, developers can focus more on the application logic rather than writing and managing complex SQL queries. Happy coding !❤️