Skip to main content

using sequelize with postgresql in node js

Using Sequelize with PostgreSQL in Node.js involves several key steps:
1. Install Dependencies:
Install Sequelize, the PostgreSQL client driver, and pg-hstore for handling JSON data:
Code

npm install sequelize pg pg-hstore
2. Configure Database Connection:
Create a configuration file (e.g., config/db.config.js) to store your database credentials and connection settings:
JavaScript

module.exports = {
  HOST: "localhost",
  USER: "postgres",
  PASSWORD: "your_password",
  DB: "your_database_name",
  dialect: "postgres",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};
3. Initialize Sequelize Instance:
In your main application file or a dedicated database connection file, import Sequelize and your configuration, then create a Sequelize instance:
JavaScript

const { Sequelize } = require('sequelize');
const dbConfig = require('./config/db.config.js');

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});

module.exports = sequelize;
4. Define Sequelize Models:
Create models that represent your database tables. Each model defines the structure and attributes of a table:
JavaScript

const { DataTypes } = require('sequelize');
const sequelize = require('../path/to/sequelize'); // Adjust path as needed

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  }
});

module.exports = User;
5. Synchronize Models (Optional, for Development):
You can synchronize your models with the database to create or update tables based on your model definitions. This is useful during development but should be handled carefully in production (e.g., using migrations):
JavaScript

sequelize.sync({ force: true }) // 'force: true' drops existing tables
  .then(() => {
    console.log("Database & tables created!");
  })
  .catch(err => {
    console.error("Error syncing database:", err);
  });
6. Perform Database Operations:
You can now use your defined models to interact with the database, performing CRUD (Create, Read, Update, Delete) operations:
JavaScript

// Create a new user
const newUser = await User.create({ username: 'johndoe', email: 'john@example.com' });

// Find all users
const users = await User.findAll();

// Find a user by ID
const user = await User.findByPk(1);

// Update a user
await User.update({ email: 'newemail@example.com' }, { where: { id: 1 } });

// Delete a user
await User.destroy({ where: { id: 1 } });