notes
  • computer-networking
    • extend-wifi-with-router
    • how-the-internet-works
    • idk
    • networking-devices
    • osi-model
    • tcp-ip
    • Types of VPN
  • databases
    • Foreign Keys
    • Redis
    • simple-queries
  • devops
    • ansible
    • Manual deployment
    • docker
    • Workflow file
    • nginx
    • promethues-grafana
    • terraform
  • hardware
    • Power
  • home-server
    • proxmox-basics
    • proxmox-setup
    • storage
  • languages-frameworks
    • programming-paradigms
    • programming-languages
      • Regex Notes
      • c
        • basics
        • pointers-memory
      • cpp
        • basics
        • running-cpp
      • php
        • basics
        • choizez
        • frameworks
          • laravel
      • python
        • venv
        • concepts
          • Using lambda
        • frameworks
          • django
            • django
            • start
      • java
        • advanced
          • functional-programming
          • reactive-programming
        • concepts
          • how-java-works
          • serialization
          • sockets
          • threads
        • extra
          • collection-framework
          • generics-and-wildcards
          • Regular Expressions (Regex)
          • streams
        • frameworks
          • orm
        • fundamentals
          • OOP
          • conditionals
          • data-structures
          • data-types
          • exceptions
          • files
          • Functions (aka method)
          • Loops
          • packages
          • type-casting
      • javascript
        • frameworks
          • morgan
          • Using Sequelize with PostgreSQL in JavaScript
  • operating-system
    • basics
    • linux-directories
    • Basic Unix Terminal Commands
  • others
    • dark-web
    • piracy
  • system-design
    • system-design
  • web-dev
    • full-stack
  • books
    • sicp
      • Recursion thought process
      • 1
        • 1.1
        • 1.2
        • 1.3
      • 2
        • 2.1
  • certifications
    • aws-certified-cloud-practitioner
      • core-services
      • other-services
    • comptia-a+
      • Cloud
      • hardware
      • Important terms
      • Important terms
      • Troubleshooting
  • cloud
    • aws
      • aws-cli
      • aws-ec2-deployment
  • dsa
    • algorithms
      • back-tracking
      • bfs
      • Binary Search
      • bit-manipulation
      • Bubble sort
      • bucket-sort
      • counting-sort
      • dfs
      • Divide & Conquer
      • djikstras-algorithm
      • dynamic-programming
      • external-sorting
      • greedy-algorithm
      • Heap sort
      • Insertion sort
      • kadanes-algorithm
      • Merge sort
      • Permutation
      • quick-sort
      • Radix Sort
      • recurrence-relation
      • recursion
      • Selection sort
      • sliding-window
      • subset
      • time-space-complexity
      • topological-sort
      • tree-traversals
      • Two Pointers Technique
    • data-structures
      • data-structures
  • security
    • authentication
      • What is JWT (JSON Web Token)?
    • software-architecture-design
      • design-patterns
Powered by GitBook
On this page
  • Installation
  • Setup
  • Define Models
  • CRUD Operations
  • Advanced Features
  1. languages-frameworks
  2. programming-languages
  3. javascript
  4. frameworks

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%",
        },
      },
    });
PreviousmorganNextoperating-system

Last updated 1 month ago