Using Sequelize with PostgreSQL in JavaScript
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:
npm install sequelize pg
Setup
Import Sequelize:
const { Sequelize } = require("sequelize");
Create Sequelize Instance:
const sequelize = new Sequelize({ database: "your_database_name", username: "your_username", password: "your_password", host: "localhost", dialect: "postgres", });
Define Models
Define a Model:
const User = sequelize.define("User", { // Define model attributes firstName: { type: Sequelize.STRING, }, lastName: { type: Sequelize.STRING, }, // ... });
Sync Models with Database:
// Synchronize models with the database sequelize.sync({ force: true }).then(() => { console.log("Database and tables synced!"); });
CRUD Operations
Create a Record:
const newUser = await User.create({ firstName: "John", lastName: "Doe" });
Read Records:
const allUsers = await User.findAll();
const specificUser = await User.findOne({ where: { firstName: "John" } });
Update a Record:
await User.update({ lastName: "Smith" }, { where: { firstName: "John" } });
Delete a Record:
await User.destroy({ where: { firstName: "John" } });
Advanced Features
Associations:
Define associations between models:
User.hasMany(Project); Project.belongsTo(User);
Query with Conditions:
Use Sequelize operators for complex queries:
const Op = Sequelize.Op; const users = await User.findAll({ where: { lastName: { [Op.like]: "D%", }, }, });
Last updated