Lesson 15 / 33

Database Integration

Connect NestJS to databases via TypeORM or other ORMs.

TypeORM setup

Install @nestjs/typeorm and typeorm. Configure in your root module.

npm install @nestjs/typeorm typeorm pg

Register with NestJS

Use TypeOrmModule.forRoot() to configure the connection.

import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'user',
      password: 'password',
      database: 'mydb',
      entities: [User, Post],
      synchronize: true
    })
  ]
})
export class AppModule {}