Sequelize is an Object-Relational Mapping (ORM) library for Node.js, providing a powerful and intuitive way to interact with relational databases by mapping JavaScript objects to database tables.
It simplifies database operations, supports multiple database systems, and enhances code readability and maintainability by abstracting away the complexities of SQL queries.
Installation
Install Sequelize and the PostgreSQL driver using npm:
Copy npm install sequelize pg
Setup
Import Sequelize:
Copy const { Sequelize } = require("sequelize");
Create Sequelize Instance:
Copy const sequelize = new Sequelize({
database: "your_database_name",
username: "your_username",
password: "your_password",
host: "localhost",
dialect: "postgres",
});
Define Models
Define a Model:
Copy const User = sequelize.define("User", {
// Define model attributes
firstName: {
type: Sequelize.STRING,
},
lastName: {
type: Sequelize.STRING,
},
// ...
});
Sync Models with Database:
Copy // Synchronize models with the database
sequelize.sync({ force: true }).then(() => {
console.log("Database and tables synced!");
});
CRUD Operations
Create a Record:
Copy const newUser = await User.create({ firstName: "John", lastName: "Doe" });
Read Records:
Copy const allUsers = await User.findAll();
Copy const specificUser = await User.findOne({ where: { firstName: "John" } });
Update a Record:
Copy await User.update({ lastName: "Smith" }, { where: { firstName: "John" } });
Delete a Record:
Copy await User.destroy({ where: { firstName: "John" } });
Advanced Features
Associations:
Define associations between models:
Copy User.hasMany(Project);
Project.belongsTo(User);
Query with Conditions:
Use Sequelize operators for complex queries:
Copy const Op = Sequelize.Op;
const users = await User.findAll({
where: {
lastName: {
[Op.like]: "D%",
},
},
});