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 impl
4 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 Content Wha
5 min read
Fetch and Send with Firestore using ReactJS
To perform fetch and send with Firestore using React require sending and receving data on the firestore database. Firestore is a NoSQL database developed by Google as an alternative to the Firebase database. It has been designed to provide a better developer experience and simplify the development p
4 min read
NestJS Tutorial
NestJS is a progressive NodeJS framework for building efficient, reliable, and scalable server-side applications. It combines elements of object-oriented programming, functional programming, and functional reactive programming to provide a robust architecture for building server-side applications. T
7 min read
Finding Objects using Lodash with Nested Properties
Finding objects by nested properties is a common task when dealing with complex data structures like deeply nested arrays or objects. Lodash, a popular JavaScript utility library, provides methods that simplify working with deeply nested data. PrerequisitesNode.jsNPMLodash LibraryInstall Lodash:Open
2 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
Expense Tracker using Next.js
The Expense Tracker project is a NextJS-based web application designed to help users manage their finances more effectively. Users can easily add and delete expenses and income, allowing them to track their spending habits and view a summary of their expenses. This project not only provides a practi
4 min read