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

  1. Import Sequelize:

    const { Sequelize } = require("sequelize");
  2. Create Sequelize Instance:

    const sequelize = new Sequelize({
      database: "your_database_name",
      username: "your_username",
      password: "your_password",
      host: "localhost",
      dialect: "postgres",
    });

Define Models

  1. Define a Model:

    const User = sequelize.define("User", {
      // Define model attributes
      firstName: {
        type: Sequelize.STRING,
      },
      lastName: {
        type: Sequelize.STRING,
      },
      // ...
    });
  2. Sync Models with Database:

    // Synchronize models with the database
    sequelize.sync({ force: true }).then(() => {
      console.log("Database and tables synced!");
    });

CRUD Operations

  1. Create a Record:

    const newUser = await User.create({ firstName: "John", lastName: "Doe" });
  2. Read Records:

    const allUsers = await User.findAll();
    const specificUser = await User.findOne({ where: { firstName: "John" } });
  3. Update a Record:

    await User.update({ lastName: "Smith" }, { where: { firstName: "John" } });
  4. Delete a Record:

    await User.destroy({ where: { firstName: "John" } });

Advanced Features

  1. Associations:

    Define associations between models:

    User.hasMany(Project);
    Project.belongsTo(User);
  2. 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