Open In App

Using TypeORM with NestJS

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. One of the powerful features of NestJS is its ability to easily integrate with databases using TypeORM, a popular ORM (Object-Relational Mapping) tool. This article will guide you through the process of using TypeORM with NestJS, including setup, configuration, and basic usage.

What is TypeORM?

TypeORM is an ORM for TypeScript and JavaScript (ES7, ES6, ES5). It supports various databases such as MySQL, MariaDB, PostgreSQL, SQLite, and Microsoft SQL Server. TypeORM allows you to work with databases using TypeScript or JavaScript and provides a repository and DataMapper pattern for working with data in a type-safe way.

Why Use TypeORM with NestJS?

  • TypeScript Support: Both NestJS and TypeORM are built with TypeScript, providing type safety and improved developer experience.
  • Active Record and Data Mapper Patterns: TypeORM supports both patterns, giving flexibility in how you model your data.
  • Easy Integration: NestJS has built-in support for TypeORM, making it straightforward to set up and configure.

Setting Up TypeORM with NestJS

Step 1: Create a New NestJS Project

If you haven't already, create a new NestJS project using the Nest CLI:

npm i -g @nestjs/cli
nest new my-project

Step 2: Navigate to the project directory

cd my-project

Step 3: Install TypeORM and the Database Driver

Install TypeORM and the relevant database driver. For this example, we'll use PostgreSQL:

npm install --save @nestjs/typeorm typeorm @nestjs/mongoose mongoose @nestjs/config

Step 4: Create a Repository

NestJS uses repositories to interact with the database. Create a new module, service, and controller for the User entity:

nest generate module user
nest generate service user
nest generate controller user

Folder Structure

ewr5t
Folder Structure

Dependencies

"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.0.0",
"@nestjs/mongoose": "^10.0.10",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/typeorm": "^10.0.2",
"mongoose": "^8.5.1",
"pg": "^8.12.0",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20"
}

Example

JavaScript
//app.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { User } from './entities/user.entity';

@Module({
    imports: [
        ConfigModule.forRoot({
            isGlobal: true,
        }),
        TypeOrmModule.forRoot({
            type: 'mongodb',
            url: 'your Mongodb uri',
            entities: [User],
            synchronize: true,
            useNewUrlParser: true,
            useUnifiedTopology: true,
        }),
        UserModule,
    ],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule { }
JavaScript
//enities/user.entity.ts

import { Entity, ObjectIdColumn, ObjectId, Column } from 'typeorm';

@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectId;

    @Column()
    name: string;

    @Column()
    email: string;
}
JavaScript
//user.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from '../entities/user.entity';

@Module({
    imports: [TypeOrmModule.forFeature([User])],
    providers: [UserService],
    controllers: [UserController],
})
export class UserModule { }
JavaScript
// user.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { ObjectId } from 'mongodb';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private userRepository: Repository<User>,
    ) { }

    findAll(): Promise<User[]> {
        return this.userRepository.find();
    }

    findOne(id: string): Promise<User> {
        return this.userRepository.findOneBy({ id: new ObjectId(id) });
    }

    create(user: User): Promise<User> {
        return this.userRepository.save(user);
    }

    async remove(id: string): Promise<void> {
        await this.userRepository.delete({ id: new ObjectId(id) });
    }
}
JavaScript
// user.controller.ts

import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from '../entities/user.entity';

@Controller('users')
export class UserController {
    constructor(private readonly userService: UserService) { }

    @Get()
    findAll(): Promise<User[]> {
        return this.userService.findAll();
    }

    @Get(':id')
    findOne(@Param('id') id: string): Promise<User> {
        return this.userService.findOne(id);
    }

    @Post()
    create(@Body() user: User): Promise<User> {
        return this.userService.create(user);
    }

    @Delete(':id')
    remove(@Param('id') id: string): Promise<void> {
        return this.userService.remove(id);
    }
}

To start the application run the following command.

npm run start

Output


Next Article

Similar Reads