0
0
NestjsHow-ToBeginner ยท 4 min read

How to Connect to Database in NestJS: Simple Guide

To connect to a database in NestJS, use the @nestjs/typeorm package and configure the TypeOrmModule in your root module with your database details. This sets up the connection and allows you to use repositories or entities for database operations.
๐Ÿ“

Syntax

Use TypeOrmModule.forRoot() in your root module to configure the database connection. Provide an object with connection details like type, host, port, username, password, and database. Import this module to enable database access throughout your app.

typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'user',
      password: 'pass',
      database: 'testdb',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
  ],
})
export class AppModule {}
๐Ÿ’ป

Example

This example shows how to connect to a PostgreSQL database using TypeOrmModule in NestJS. It demonstrates setting up the connection and defining a simple entity to interact with the database.

typescript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

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

  @Column()
  name: string;
}

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'user',
      password: 'pass',
      database: 'testdb',
      entities: [User],
      synchronize: true,
    }),
    TypeOrmModule.forFeature([User]),
  ],
})
export class AppModule {}
Output
NestJS application starts and connects to PostgreSQL database; User entity table is created automatically.
โš ๏ธ

Common Pitfalls

  • Forgetting to install @nestjs/typeorm and typeorm packages.
  • Not including entities in the entities array, so tables are not created.
  • Setting synchronize: true in production can cause data loss; use migrations instead.
  • Incorrect database credentials or host cause connection failures.
  • Not importing TypeOrmModule.forFeature() in feature modules to access repositories.
typescript
/* Wrong: Missing entities array */
TypeOrmModule.forRoot({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'user',
  password: 'pass',
  database: 'testdb',
  synchronize: true,
}),

/* Right: Include entities */
TypeOrmModule.forRoot({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'user',
  password: 'pass',
  database: 'testdb',
  entities: [User],
  synchronize: true,
}),
๐Ÿ“Š

Quick Reference

Tips for connecting to database in NestJS:

  • Install @nestjs/typeorm and your database driver (e.g., pg for PostgreSQL).
  • Use TypeOrmModule.forRoot() in AppModule with correct config.
  • Define entities with decorators like @Entity(), @Column().
  • Use TypeOrmModule.forFeature() in feature modules to inject repositories.
  • Set synchronize: false in production and use migrations.
โœ…

Key Takeaways

Use TypeOrmModule.forRoot() with your database config to connect in NestJS.
Always include your entities in the connection options to enable table creation.
Install both @nestjs/typeorm and the database driver package before connecting.
Use TypeOrmModule.forFeature() in modules to access repositories for entities.
Avoid synchronize: true in production; prefer migrations for schema changes.