Skip to main content

NestJS API CRUD Operation Using PostgreSQL Relational Database

NestJS API is a server-side framework that runs on NodeJS frameworks like Express. NestJS application has the ability to talk with both SQL and Non-SQL databases.

Here we will develop a sample NestJS API application that communicates with the PostgreSQL relational database.

NestJS Database Communication Flow:

The 'pg'(PostgreSQL NodeJS library) library was used for communicating with the PostgreSQL database. The 'typeorm'(NodeJS library) library is a framework used for querying the database or manipulating the database using the specified database library(in our case 'pg' node library). The 'typeorm' will be used for all database configurations also. The '@nestjs/typeorm'(NestJS ORM library) is an overlay or wrapper for the 'typeorm'(NodeJS library). By using '@nestjs/typeorm' it gives the advantage of Typescript compatibility and additional feature over 'typeorm'(NodeJS library). So while implementing NestJS application in max scenarios we will only use the '@nestjs/typeorm' library which will internally communicate with 'typeorm'(NodeJS library).

PostgreSQL Database Using ElephantSQL Cloud Service:

So for our application, we need to set up a PostgreSQL relational database. Here I'm going to set up a free cloud service PostgreSQL database provided by ElephantSQL for our demo purpose. It is a very easy setup, to do it takes 3-5minutes to setup, click here for steps to configure the ElephantSQL cloud service.

Create A Sample NestJS App:

Let's begin our sample by creating a NestJS application. Here we use NestJS CLI(command line interface) to create app.
Command To Install Nest CLI:

npm i -g @nestjs/cli
NestJS CLI Command To Create APP:

nest new your_project_name
By default NestJS application configured to run on portnumber '3000'. So execute the below command to start the application.
Commands To Start App:

npm run start
npm run start:dev ---> runs application in watch mode prefered for development time
npm run start:prod ---> production mode 

Npm Packages:

Install the following npm packages that are needed to accomplish our sample NestJS application.
Install NestJS Typeorm:

npm install --save @nestjs/typeorm
Install NodeJS Typeorm:

npm install --save typeorm
Install NodeJS PostgreSQL:

npm install --save pg

typeorm Decorators For Table Entities:

To make our typescript entity or model as table related entity, then we need to use decorators that are provided by the 'typeorm'(node js library).

@Entity() - This decorator is used to mark classes that will be an entity(table or document depends on database type). A database scheme will be created for all classes decorate with it, and the repository can be retrieved and used for it.

@PrimaryColumn() - This decorator is used to mark the property of an entity as a primary column of the table. It has the capability of the incremental integer value to save.

@Column() - This decorator is used to mark the property of class as the column of the table.

Create An Employee Table Entity:

In this sample, we are going to develop CRUD operations on the Employee table in the PostgreSQL relational database.

As a first step lets create a typescript Employee class that represents the database table.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

export class Employee {
id: number; @Column() name: string; @Column() salary: number; @Column() age: number; }
  • (Line: 1) all required decorators are imported from the 'typeorm'(NodeJS library)
  • (Line: 3) typescript class Employee decorated with '@Entity()' decorator to make it as table class.
  • (Line: 5) 'id' property decorated with '@PrimaryColumn' decorator to make compatible with the primary column of the table.
  • @column() decorator was used on all other properties of the typescript class to represent the table columns.

TypeOrmModule Of @nestjs/typeorm:

TypeOrmModule of @nestjs/typerorm(NestJs library) will be used to configure database settings, register table entities, register injectable repositories of entity types, etc. TypeOrmModule implements static overloaded methods like:
  • forRoot() - this method takes configuration like database settings to set up communication between the NestJS application and the database. This method always registered in the parent or root module of the application like the 'app module'.
  • forFeature() - this method is similar to the forRoot() method but it will be registered for child modules of the 'appmodule'.
  • forRootAsync() - this async form forRoot() method.

Add PostgreSQL Configuration To AppModule:

To establish communication with the PostgreSQL database need to add configuration in TypeOrmModule at app.module.ts file to register globally.
import { TypeOrmModule } from '@nestjs/typeorm';
import { Employee } from './Employee/employee.entity';
// some code hidden for display purpose
  imports: [
      type: 'postgres',
      host: '',
      port: 5432,
      username: '-----------',
      password: '-----------',
      database: '-----------',
      entities: [Employee],
export class AppModule {}
  • (Line: 7) 'type' defines the database will be used since we are using the PostgreSQL database so we can pass the constant value of 'postgres'. 
  • (Line: 8) 'host' database server hosted
  • (Line: 9) the port number, '5432' is the default port number for the PostgreSQL database.
  • (Line: 10&11&12) database username, password, name of the database
  • (Line: 13) entities of the database need to register, it takes an array of entity types.
  • Click here for identifying PostgreSQL configurations

Pre-defined Repository Of typeorm:

The 'typeorm'(NodeJS library) provides Pre-defined 'Repository<TEntity>'. This pre-defined 'Repository' is supposed to work with our entity objects. It responsibilities are like 'find entities', 'insert', 'update', 'delete', etc.

InjectRepository Decorator From @nestjs/typeorm:

The '@nestjs/typeorm'(NestJS library) provides 'InjectRepository' decorator. This 'InjectRepository' decorator helps to inject the 'Repository<TEntity>' from 'typeorm'(NodeJS library) into the service files constructor of our application.

Create EmployeeService:

In general, all our logical code will be implemented in our 'service' files.
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

export class EmployeeService {
  constructor(@InjectRepository(Employee) private employeeRepo: Repository<Employee>) {}
  • (Line: 6) 'Injectable' decorator used on 'EmployeeService' to make it as an injectable service
  • (Line: 8) 'Repository<Employee>' injected into the service class with the help of '@InjectRepository()' decorator.

Add Fetch All Employee Logic:

Now in service using the repository, we are going to query the PostgreSQL relational database. Repository from 'typeorm'(NodeJS library) is built with a predefined query method which makes our logic simple and easy for database communication. Now here we will implement the method to fetch all our employee data.
import { Employee } from './employee.entity';
// code hidden for display purpose
export class EmployeeService {
   findAll(): Promise<Employee[]> {
    return this.employeeRepo.find();
  • The 'find()' method from the repository which will take optional filter parameters to query against the database. If no filter parameters passed it return all the data from the database.
  • The 'find()' method returns a promise of an array of the entity type.

Create Employee Controller With Read Operation:

Now let's add the Employee controller for our sample application. Create an endpoint to read all the employees from the PostgreSQL relational database.
import { Controller, Get } from '@nestjs/common';
import {EmployeeService} from './employee.service';
import {Employee} from './employee.entity';

export class EmployeeController {
    constructor(private readonly employeeService: EmployeeService){}

    async getAll():Promise<Employee[]>{
        return await this.employeeService.findAll();
  • '@Controller()' decorator that makes class as Nest controller that can receive the inbound request and produce the response.
  • '@Get()' decorator is a route handler decorator. Routes Http Get request to the specified path.
  • (Line: 7) injected 'EmployeeService'
  • (Line: 9-12)Http method that executes read operation to fetch all the employee data.

Create An Employee Module:

In NestJS implementation each business logic will be developed as simple separate modules. These Modules acts entry point to register all configuration like 'controllers', 'services', 'entities', etc. So here we need to create an Employee module for our business.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { EmployeeController } from './employee.controller';
import { Employee } from './employee.entity';
import { EmployeeService } from './employee.service';

  imports: [TypeOrmModule.forFeature([Employee])],
  providers: [EmployeeService],
  controllers: [EmployeeController],
export class EmployeeModule {}
  • 'TypeOrmModule.forFeature([Employee])' makes the 'Emplyee' entity schema available to 'Repository' from the 'typeorm'(NodeJS library) to query the database.
  • 'EmployeeService' registered to providers array to load the service for the Employee module.
  • 'EmployeeController' registered to controllers array to expose the routes.

Register Child Modules To AppModule:

Now to load or expose the child modules in an application we need to import those child modules in the app.module.ts file.
import { EmployeeModule } from './Employee/employee.module';

// code hidden for display purpose
  imports: [
export class AppModule {}
Now start the application and access the newly created endpoint and output shows as below.

Create Operation:

Now we are going to implement a create operation to create new employees.
'insert()' method provided by the 'Repository' imported from 'typeorm'(NodeJS library). This method inserts a given entity. Executes fast and efficient Insert queries. Doesn't check if the entity exists in the database, so the query will fail if a duplicate entity tries to insert.

Now in the controller let's add a post-action method.
import { Controller, Get, Post, Body, HttpCode } from '@nestjs/common';

createEmployee(@Body() newEmployee:any){
  • '@Post()' request handler decorator. Routes Http Post request to the specified path.
  • '@HttpSatatusCode' request method decorator. Defines the Http response status code. Overrides default status code for the decorated request method. '201' status code stands for created successfully.
  • '@Body()' route handler parameter decorator. Extract the entire body object from the request object and populate the decorated parameter with the value of the body.

Update Operation:

Add the following code to update a record.
'update()' method from 'Repository' imported from 'typeorm'. This method is an overloaded method. It has the capability to do a partial update without effecting other column's data.
updateEmployee(@Body() employeeToUpdate:any){

Delete Operation:

'delete()' method of 'Repository' from 'typeorm'. Bypassing the primary key id is enough to remove the record from the database.
deleteEmployee(@Param('id') id){
  • '@Delete()' route handler decorator. Routes Http Delete requests to the specified path.
  • '@Param()' this decorator is to extract the data from the route.

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on creating a sample of NestJS CRUD operations using the relational database PostgreSQL. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:


  1. This was well details article. It unveiled alot to help understand NESTJS


Post a Comment

Popular posts from this blog

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

NestJS File Upload

In this article, we are going to understand the steps to create a file uploading endpoint in the NestJS application. Key Features In NestJS File Upload: Let us know some key features of NestJS file upload before implementing a sample application. FileInterceptor: The 'FileInterceptor' will be decorated on top of the file upload endpoint. This interceptor will read single file data from the form posted to the endpoint. export declare function FilesInterceptor(fieldName: string, localOptions?: MulterOptions): Type<NestInterceptor>; Here we can observe the 'fieldName' first input parameter this value should be a match with our 'name' attribute value on the form file input field. So our interceptor read our files that are attached to the file input field. Another input parameter of 'MulterOptions' that provides configuration like file destination path, customizing file name, etc. FilesInterceptor: The 'FilesInterceptor' will be decorated on t

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http