CodePark/ questions / Database integration (TypeORM / Prisma)
START PRACTICINGPRACTICE
Backend question · NestJS › Database integration (TypeORM / Prisma)

How do you set up TypeORM in Nest and inject a repository into a service?

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UsersService],
})
export class UsersModule {}

@Injectable()
export class UsersService {
  constructor(@InjectRepository(User) private users: Repository<User>) {}
  findOne(id: number) { return this.users.findOneBy({ id }); }
}

Register the connection with TypeOrmModule.forRoot(), register entities with TypeOrmModule.forFeature(), then inject a repository with @InjectRepository().

The steps:

  • Install @nestjs/typeorm, typeorm and a database driver.
  • In the root module, call TypeOrmModule.forRoot() with the connection options. Or use forRootAsync() to read them from ConfigService.
  • Set autoLoadEntities: true. Nest then registers the entities from every forFeature call automatically.
  • In each feature module, call TypeOrmModule.forFeature([User]). This registers repositories for those entities in that module's scope.
  • In a service, inject one with @InjectRepository(User), typed as Repository<User>.

Don't use synchronize: true in production. It changes the database schema on startup and can lose data. Use migrations instead. A migration is a versioned script that changes the schema in a controlled way.

  • Use forRoot or forRootAsync to set up the connection.
  • Call forFeature([Entity]) in each feature module.
  • Inject with @InjectRepository(Entity), typed as Repository<Entity>.
  • The autoLoadEntities option registers entities from forFeature automatically.
  • Don't use synchronize: true in production. Use migrations instead.