Using TypeORM with NestJS
Last Updated :
29 Jul, 2024
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
Folder StructureDependencies
"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
Similar Reads
Using Mongoose with NestJS
NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It provides a solid foundation for backend development with TypeScript support, built-in decorators, and a modular architecture. Mongoose, on the other hand, is a powerful Object Data M
3 min read
Using WebSockets in NestJS
WebSocket is a protocol used for real-time communication between client and server. It is a better approach to serve real-time data than short-polling and long-polling.In this article, we will be building a simple real-time Chat Application using Socket.io which is a JavaScript library used to imple
3 min read
How To Perform Unit Test in NestJS?
NestJS is a Node.js framework for building efficient, reliable and scalable server-side applications. It is built using TypeScript and It offers support for unit testing through the Jest testing framework. In this article, we will learn about performing unit testing in a NestJs.Table of ContentWhat
5 min read
Node.js with TypeScript
If you're immersed in the world of Node.js development, you're likely acquainted with the hurdles of handling and expanding a substantial codebase. A viable solution to tackle this is leveraging TypeScript, a statically-typed superset of JavaScript. TypeScript enriches the language with optional typ
6 min read
Recipe Finder using ReactJS
In this project article, we will be creating a recipe finder application using the React library. We have given the application the name "GeeksforGeeks Recipe Finder". This application is completely developed in ReactJS and mainly focuses on the functional components and also manages the various sta
5 min read
Blogging Platform using Next JS
In this project, we will explore the process of building The Blogging Platform with Next.js. Blogging Platform is a web application that allows users to create and publish blog posts. The platform provides a user-friendly interface for managing blog content and includes functionalities to create new
5 min read
Weather Forecast App using MERN Stack
This project is a simple weather application built using React.js for the frontend and Node.js with Express.js for the backend. It allows users to check the current weather and forecast for a specific city. The backend retrieves weather data from the OpenWeatherMap API and stores it in a MongoDB dat
7 min read
Chat Website using MERN Stack
The "Chat Website" project is a dynamic web application that is used for real-time communication. The MERN stack, comprised of MongoDB, Express.js, React.js, and Node.js, is a powerful combination of technologies for developing robust and scalable web applications. In this article, we'll explore the
4 min read
Note-Taking App with Status Tracker using MERN Stack
In this article, we will be creating a simple note-taking application with functionalities to create a note, delete a note, edit a note, and view the note. The project uses NodeJS as a backend server with Postman API to post and get the notes from the HTTP request. It uses ExpressJS as a framework i
15 min read
How To Use React Context In NextJS With Typescript?
React introduced Context to simply managing global consistent states in application. In this article we will how to use React Context for consistent states across various components with Next.js, the most popular and widely used React meta framework, and with TypeScript or complete type safety.Prere
4 min read