Nestjs - Typeorm 自定义连接名称

3
我有一个Nestjs数据库模块,它运行得非常完美。
@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            useFactory: () => {
                return {
                    name: 'default', // <=== here
                    type: "mysql",
                    ...
                };
            },
        }),

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

如果我将连接名称更改为除“default”以外的任何其他内容,例如“test”,则会出现错误。
@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 */ ]
  })

如果我使用TypeOrmModule.forRootAsync,错误似乎只会出现在这里。但是如果使用TypeOrmModule.forRoot,则可以正常工作!

有没有其他不同的方法来指示连接名称?我需要添加另一个连接,但由于此错误而无法执行。真的很想使用'forRootAsync'

1个回答

9

按照以下方式传递连接名称。

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

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

谢谢,那就是解决办法! - levansuper
@levansuper很高兴问题得到解决。你可以随时查看函数定义文件以了解它接受的参数。此外,你也可以接受这个解决方案。 - AZ_
2
似乎已经过时了。还有其他解决方案吗? - PptSbzzgt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接