Search code examples
node.jsnestjsconnectiontypeorm

Nestjs - Typeorm custom connection name


I have a Nestjs db Module and it works perfectly

@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            useFactory: () => {
                return {
                    name: 'default', // <=== here
                    type: "mysql",
                    ...
                };
            },
        }),

        TypeOrmModule.forFeature(entities, 'default'), // <=== here
    ],
    exports: [TypeOrmModule],
})
export class DBModule {}

if I change the connection name to anything else rather then 'default' say 'test' I get an error

@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            useFactory: () => {
                return {
                    name: 'test', // <=== here
                    type: "mysql",
                    ...
                };
            },
        }),

        TypeOrmModule.forFeature(entities, 'test'), // <=== here
    ],
    exports: [TypeOrmModule],
})
export class DBModule {}
[Nest] 10746   - 05/15/2021, 5:55:34 PM   [ExceptionHandler] Nest can't resolve dependencies of the test_UserEntityRepository (?). Please make sure that the argument testConnection at index [0] is available in the TypeOrmModule context.

Potential solutions:
- If testConnection is a provider, is it part of the current TypeOrmModule?
- If testConnection is exported from a separate @Module, is that module imported within TypeOrmModule?
  @Module({
    imports: [ /* the Module containing testConnection */ ]
  })

The error seams to only show up if I use TypeOrmModule.forRootAsync For TypeOrmModule.forRoot if works!

Is there any different way to indicate the connection name? I need to add another connection and can't do it because of this error. Really would like to use 'forRootAsync'


Solution

  • Pass the connection name as follows.

    @Module({
    imports: [
        TypeOrmModule.forRootAsync({
            name: 'test', // <=== here
            useFactory: () => {
                return {
                    type: "mysql",
                    ...
                };
            },
        }),
    
        TypeOrmModule.forFeature(entities, 'test'), // <=== here
        ],
        exports: [TypeOrmModule],
    })
    export class DBModule {}