Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 588
levansuper Avatar asked Oct 20 '25 13:10

levansuper


1 Answers

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 {}
like image 142
AZ_ Avatar answered Oct 23 '25 05:10

AZ_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!