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
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
Pipes in NestJS Pipes in NestJS help in transforming and validating data within your application. They play an important role in ensuring that data entering the system is clean, consistent, and meets the required criteria. In this article, we will explore how pipes work in NestJS, their benefits, and how to impleme
3 min read
How To Set Up Mongoose With Typescript In NextJS ? Combining Mongoose with TypeScript in a Next.js project is an intelligent approach to develop scalable, type-safe, and maintainable full-stack web applications. Mongoose offers a powerful ODM (Object Data Modeling) layer to interact with MongoDB, and TypeScript provides static typing to detect issue
5 min read
Introduction to GraphQL with NestJS NestJS is a progressive NodeJS framework that uses TypeScript to build efficient and scalable server-side applications. Combining NestJS with GraphQL, a powerful query language for APIs, offers a robust solution for creating modern, maintainable, and highly performant web applications. In this artic
3 min read
E-commerce Website using MERN Stack The project is an E-commerce website built using the MERN (MongoDB, Express.js, React, Node.js) stack. It provides a platform for users to view and purchase various products. The server-side (Node.js with Express) manages the API for product data stored in a MongoDB database. The client-side (React)
7 min read
What is NestJS? NestJS is a powerful framework for building efficient and scalable server-side applications. Developed with a focus on modern JavaScript and TypeScript, NestJS combines object-oriented programming, functional programming, and reactive programming. In this article, we will learn in-depth about NestJS
3 min read