Imagine you're building a Node.js app that needs to store data. You could write raw SQL queries, but let’s be honest…
- Writing SQL manually is a nightmare!
- Managing relationships? Too much effort!
- Switching between databases? Good luck with that!
Enter Sequelize, the superhero ORM (Object-Relational Mapping) that makes working with databases in Node.js fun, easy, and flexible!
Today, we’ll cover everything about Sequelize, including:
- What Sequelize is
- How to install and use Sequelize
- Sequelize with both CommonJS (CJS) and ES Modules (ESM)
- CRUD operations (Create, Read, Update, Delete)
- Associations (One-to-One, One-to-Many, Many-to-Many)
- Migrations & Seeders
Let’s get started!
1. What is Sequelize?
Sequelize is a popular ORM for Node.js that helps you interact with relational databases like:
- PostgreSQL
- MySQL
- MariaDB
- SQLite
- Microsoft SQL Server
Instead of writing raw SQL queries, Sequelize lets you use JavaScript to define models, relationships, and queries in a structured way.
2. Installing Sequelize in Node.js
Before using Sequelize, install the required packages.
Install Sequelize and a Database Driver
npm install sequelize
npm install mysql2 # For MySQL
npm install pg pg-hstore # For PostgreSQL
npm install sqlite3 # For SQLite
npm install tedious # For MSSQL
Choose the driver based on your database.
3. Setting Up Sequelize (CJS & ESM)
Using Sequelize with CommonJS (CJS)
In CommonJS (require
), initialize Sequelize like this:
const { Sequelize } = require("sequelize");
// Connect to the database
const sequelize = new Sequelize("database_name", "username", "password", {
host: "localhost",
dialect: "mysql", // Change to "postgres", "sqlite", "mssql" if needed
});
// Test the connection
sequelize.authenticate()
.then(() => console.log("Database connected successfully"))
.catch(err => console.error("Database connection failed", err));
module.exports = sequelize;
Using Sequelize with ES Module (ESM)
In ES Module (import
), initialize Sequelize like this:
import { Sequelize } from "sequelize";
const sequelize = new Sequelize("database_name", "username", "password", {
host: "localhost",
dialect: "mysql",
});
try {
await sequelize.authenticate();
console.log("Database connected successfully");
} catch (error) {
console.error("Database connection failed", error);
}
export default sequelize;
4. Defining a Model (Table)
A model in Sequelize represents a table in the database.
Example: Create a User
Model
const { DataTypes } = require("sequelize");
const sequelize = require("./database"); // Import Sequelize instance
const User = sequelize.define("User", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
age: {
type: DataTypes.INTEGER,
allowNull: true,
},
});
module.exports = User;
Don't forget to sync the model with the database!
sequelize.sync()
.then(() => console.log("Database synchronized 🛠"))
.catch(err => console.error("Sync failed ❌", err));
5. CRUD Operations with Sequelize
Create (Insert Data)
const newUser = await User.create({
name: "John Doe",
email: "john@example.com",
age: 30,
});
console.log("User Created:", newUser.toJSON());
Read (Get Data)
const users = await User.findAll();
console.log("All Users:", users);
Update (Modify Data)
await User.update({ age: 31 }, { where: { email: "john@example.com" } });
console.log("User Updated");
Delete (Remove Data)
await User.destroy({ where: { email: "john@example.com" } });
console.log("User Deleted ❌");
6. Defining Relationships (Associations)
Sequelize supports relationships like:
One-to-One
One-to-Many
Many-to-Many
One-to-Many Example
A User has many Posts.
const Post = sequelize.define("Post", {
title: DataTypes.STRING,
content: DataTypes.TEXT,
});
// Define Relationship
User.hasMany(Post);
Post.belongsTo(User);
// Sync Models
sequelize.sync();
Now you can associate posts with users!
7. Migrations & Seeders (Managing Database Schema)
Sequelize provides migrations to manage database schema changes and seeders to add dummy data.
Install Sequelize CLI
npm install --save-dev sequelize-cli
Initialize Sequelize
npx sequelize-cli init
This creates a migrations/ and seeders/ folder.
Create a Migration
npx sequelize-cli model:generate --name User --attributes name:string,email:string
Run the migration:
npx sequelize-cli db:migrate
Now, your database is structured properly!
8. Why Use Sequelize?
- No more raw SQL queries – Write JavaScript instead!
- Easily switch between databases – Change
dialect: "mysql"
to"postgres"
. - Built-in relationships and validations.
- Works with both CommonJS and ES Modules.
- Perfect for both small and large projects!
Conclusion: Become a Sequelize Master!
- Sequelize makes database management easy in Node.js.
- Works with MySQL, PostgreSQL, SQLite, and MSSQL.
- Supports CRUD, relationships, migrations, and seeders.
-
Can be used with both CJS (
require
) and ESM (import
).
Now, go forth and build awesome apps with Sequelize!
#HappyCoding!
0 Comments