'Why do I get `RepositoryNotFoundError` error in NestJS-TypeORM app?

Okay so I'm using TYPEORM_ prefixed environment variables to register TypeOrmModule into my app. Then I'm loading entities using .forFeature() like so:

@Module({
  imports: [TypeOrmModule.forFeature([Foo])],
  controllers: [FooController],
  providers: [FooService],
  exports: [TypeOrmModule],
})
export class FooModule {}

No matter whether I use forRoot() or forRoot({ autoLoadEntities: true }) in AppModule, I get RepositoryNotFoundError: No repository for "Foo" was found. Looks like this entity is not registered in current "default" connection? error while working with the dev server. Any idea what's going on? My service looks like:

@Injectable()
export class FooService {
  constructor(@InjectRepository(Foo) private readonly fooRepository: Repository<Foo>) {}
}

I tried the followings as single and/or combined, still didn't solve the issue.

  • Put a name in @Entity() decorator.
@Entity('foo')
export class Foo {}
  • Try forRootAsync().
@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: async () =>
        Object.assign(await getConnectionOptions(), { autoLoadEntities: true }),
    }),
    FooModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  • Pass 'default' to forFeature().
@Module({
  imports: [TypeOrmModule.forFeature([Foo], 'default')],
  controllers: [FooController],
  providers: [FooService],
  exports: [TypeOrmModule],
})
export class FooModule {}
  • Try using entities key in forRoot().
@Module({
  imports: [
    TypeOrmModule.forRoot({ entities: [Foo] }),
    FooModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}


Solution 1:[1]

try to define connectionName inside getConnectionOptions

example:

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: async () =>
        Object.assign(await getConnectionOptions('default'), { autoLoadEntities: true }),
    }),
    FooModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mnigos