@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,typeormand a database driver. - In the root module, call
TypeOrmModule.forRoot()with the connection options. Or useforRootAsync()to read them fromConfigService. - Set
autoLoadEntities: true. Nest then registers the entities from everyforFeaturecall 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 asRepository<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
forRootorforRootAsyncto set up the connection. - Call
forFeature([Entity])in each feature module. - Inject with
@InjectRepository(Entity), typed asRepository<Entity>. - The
autoLoadEntitiesoption registers entities fromforFeatureautomatically. - Don't use
synchronize: truein production. Use migrations instead.
Read more
- Database (https://docs.nestjs.com/techniques/database)docs.nestjs.com
- TypeORM (https://typeorm.io/)typeorm.io