Integrating NestJS with Sequelize ORM and PostgreSQL

Integrating NestJS with Sequelize ORM and PostgreSQL

“Learn how to integrate NestJS with Sequelize ORM and PostgreSQL step-by-step. Simplify database operations, create models, and build robust APIs with this beginner-friendly guide. Perfect for developers working with TypeScript and backend frameworks.”

Introduction: Making Apps Talk to Databases

Imagine you have a big toy box (your database), and you need a friendly robot (NestJS) to help you find and organize your toys quickly. To make this robot even smarter, you give it a cool translator tool called Sequelize ORM. It helps the robot understand the language of your toy box, PostgreSQL.

In this blog, we’ll learn how to set up a NestJS app with Sequelize ORM to work with PostgreSQL. Don’t worry; I’ll explain it like a fun story!


1. Why NestJS + Sequelize + PostgreSQL?

  • NestJS: The clever robot that organizes your app. It’s great at handling tasks.
  • Sequelize ORM: The translator that helps NestJS talk to the database in simple sentences.
  • PostgreSQL: The toy box where all your toys (data) live.

2. Setting It All Up: Step-by-Step

Step 1: Start a New NestJS Project

First, create a new NestJS project by running:

npx @nestjs/cli new my-app
cd my-app

This creates your robot (NestJS) with a basic setup.

Step 2: Install Necessary Packages

We need to install Sequelize and PostgreSQL packages:

npm install @nestjs/sequelize sequelize sequelize-typescript pg pg-hstore

Here’s what they do:

  • @nestjs/sequelize: Makes Sequelize work with NestJS.
  • sequelize: The ORM itself.
  • sequelize-typescript: Adds TypeScript support for Sequelize.
  • pg and pg-hstore: Help Sequelize connect to PostgreSQL.

Step 3: Set Up the Database

Make sure PostgreSQL is installed on your computer. Create a database:

CREATE DATABASE my_app_db;

Step 4: Configure Sequelize in NestJS

In src/app.module.ts, configure Sequelize:

import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';

@Module({
imports: [
SequelizeModule.forRoot({
dialect: 'postgres',
host: 'localhost',
port: 5432,
username: 'your_username',
password: 'your_password',
database: 'my_app_db',
autoLoadModels: true,
synchronize: true,
}),
],
})
export class AppModule {}
  • autoLoadModels: true: Automatically loads all models.
  • synchronize: true: Syncs models with the database (great for development).

Step 5: Create a Toy (Model)

Let’s create a model to represent toys in our database:

nest g module toys
nest g service toys
nest g controller toys

Then create a toy.model.ts in the toys folder:

import { Table, Column, Model } from 'sequelize-typescript';

@Table
export class Toy extends Model {
@Column
name: string;

@Column
color: string;

@Column
price: number;
}

Step 6: Connect Model to the App

In toys.module.ts, add the model:

import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { ToysService } from './toys.service';
import { ToysController } from './toys.controller';
import { Toy } from './toy.model';

@Module({
imports: [SequelizeModule.forFeature([Toy])],
providers: [ToysService],
controllers: [ToysController],
})
export class ToysModule {}

Step 7: Build API Endpoints

In toys.controller.ts, add basic CRUD endpoints:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { ToysService } from './toys.service';
import { Toy } from './toy.model';

@Controller('toys')
export class ToysController {
constructor(private readonly toysService: ToysService) {}

@Post()
create(@Body() toy: Toy) {
return this.toysService.createToy(toy);
}

@Get()
findAll() {
return this.toysService.getAllToys();
}
}

In toys.service.ts, write methods:

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Toy } from './toy.model';

@Injectable()
export class ToysService {
constructor(@InjectModel(Toy) private toyModel: typeof Toy) {}

createToy(toy: Toy) {
return this.toyModel.create(toy);
}

getAllToys() {
return this.toyModel.findAll();
}
}

Step 8: Test Your API

Run the app:

npm run start

Test with tools like Postman or Thunder Client. You can create toys and view them!


3. Interview Questions and Answers

Q1: What is Sequelize ORM, and why is it used?

  • A: Sequelize ORM is a library that helps manage database operations using JavaScript/TypeScript instead of SQL queries. It simplifies CRUD operations and supports multiple databases like PostgreSQL.

Q2: How do you connect Sequelize with PostgreSQL in NestJS?

  • A: Install required packages (@nestjs/sequelize, sequelize, pg), then configure SequelizeModule in app.module.ts with database credentials.

Q3: What does autoLoadModels do in SequelizeModule configuration?

  • A: It automatically loads all models into Sequelize, so you don’t need to manually register each one.

Q4: What is the purpose of sequelize-typescript?

  • A: It adds TypeScript support to Sequelize, allowing you to define models as TypeScript classes.

Q5: How do you sync models with the database in NestJS?

  • A: Use synchronize: true in the SequelizeModule configuration. It ensures models match the database schema (only recommended for development).

4. Companies Asking About NestJS + Sequelize + PostgreSQL

  1. Globant
  2. TCS (Tata Consultancy Services)
  3. Infosys
  4. Wipro
  5. Cognizant

5. Conclusion

Integrating NestJS with Sequelize and PostgreSQL is like setting up a robot to help organize your toy box. By following these steps, you’ll have a powerful system that’s ready to handle data with ease. Good luck, and happy coding! 🚀

Interested in learning more about Microservices and NestJS? Check out our latest blogs for more in-depth guides, tutorials, and best practices on building scalable applications with NestJS and microservices.

Leave a Reply

Your email address will not be published. Required fields are marked *