0
0
NestJSframework~5 mins

TypeORM module setup in NestJS

Choose your learning style9 modes available
Introduction

TypeORM helps your NestJS app talk to databases easily. Setting it up connects your app to the database so you can save and get data.

You want to store user info in a database.
You need to read and write data in a structured way.
You want to use a database without writing raw SQL queries.
You are building a backend that needs to manage data persistently.
Syntax
NestJS
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'database_type',
      host: 'host_address',
      port: database_port,
      username: 'your_username',
      password: 'your_password',
      database: 'database_name',
      entities: [Entity1, Entity2],
      synchronize: true,
    }),
  ],
})
export class AppModule {}

forRoot sets up the database connection globally.

synchronize: true auto-creates tables but use only in development.

Examples
Connects to a local PostgreSQL database named 'testdb' with a User entity.
NestJS
TypeOrmModule.forRoot({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'secret',
  database: 'testdb',
  entities: [User],
  synchronize: true,
})
Connects to a remote MySQL database without auto-syncing tables.
NestJS
TypeOrmModule.forRoot({
  type: 'mysql',
  host: 'db.example.com',
  port: 3306,
  username: 'admin',
  password: 'pass123',
  database: 'myapp',
  entities: [Product, Order],
  synchronize: false,
})
Sample Program

This example sets up TypeORM with a SQLite database and a simple User entity. It auto-creates the table for User when the app runs.

NestJS
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'data.sqlite',
      entities: [User],
      synchronize: true,
    }),
  ],
})
export class AppModule {}

// user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}
OutputSuccess
Important Notes

Always keep synchronize: false in production to avoid data loss.

Entities are classes that represent database tables.

Use environment variables to keep database credentials safe.

Summary

TypeORM module setup connects your NestJS app to a database.

Use TypeOrmModule.forRoot() with database details and entities.

Set synchronize: true only during development for auto table creation.