首页 文章

NestJS TypeORM:使用两个或更多数据库?

提问于
浏览
3

我在2天之内尝试解决这个问题,也许我只是错过了这一点 .

我的目标是编写一个NestJS应用程序(包含TypeORM),为我的两个或三个小项目提供RestAPI,而不是为每个项目编写一个NestJS-App .

到目前为止,应用程序已经准备就绪,可以很好地处理单个项目(它们驻留在具有实体,控制器,服务,模块的子文件夹中),但我无法让它与所有这些项目一起运行 .

这一点似乎是配置,我正在使用 ormconfig.json

[ {
    "name": "Project1",
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "<username>",
    "password": "<pwd>",
    "database": "<database>",
    "synchronize": false,
    "entities": ["project1/*.entity.ts"],
    "subscribers": ["project1/*.subscriber.ts"],
    "migrations": ["project1/migrations/*.ts"],
    "cli": { "migrationsDir": "project1/migrations" }
}, {
    "name": "project2",
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "<another-username>",
    "password": "<another-pwd>",
    "database": "<another-database>",
    "synchronize": false,
    "entities": ["project2/*.entity.ts"],
    "subscribers": ["project2/*.subscriber.ts"],
    "migrations": ["project2/migrations/*.ts"],
    "cli": { "migrationsDir": "project2/migrations"
    } ]

错误消息说:

[ExceptionHandler]无法找到连接默认值,因为它未在任何orm配置文件中定义

当然无法找到“默认”,因为我提供了两个与“默认”不同的唯一名称的配置 .

ApplicationModule 我可以提供连接的名称,如下所示:

TypeOrmModule.forRoot( { name: "project1" } ),

但那时它只适用于一个项目 .

我可以将所有内容混合在一个配置中,但之后我会在一个数据库中拥有所有内容,为所有人提供相同的用户并且可能混淆实体...

有人能给我一个如何解决这个问题的提示吗?也许在每个模块中使用 getConnection(<name>) ,但是如何启动ApplicationModule呢?

亲切的问候,
sagerobert

1 回答

  • 3

    我刚刚尝试使用多个数据库和 ormconfig.json 设置TypeORM,它根本不适用于我 . 它似乎总是使用 default 连接,当没有找到默认(=没有显式名称)连接时,它抛出了相应的错误 .

    虽然我在 app.module.ts 中定义了连接(我删除了 ormconfig.json ),但确实有效:

    imports: [
      ...,
      TypeOrmModule.forRoot({
        name: 'Project1',
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: '<username>',
        password: '<pwd>',
        database: '<database>',
        synchronize: false,
        entities: ['project1/*.entity.ts'],
        subscribers: ['project1/*.subscriber.ts'],
        migrations: ['project1/migrations/*.ts'],
        cli: { migrationsDir: 'project1/migrations' },
      }),
      TypeOrmModule.forRoot({
        name: 'project2',
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: '<another-username>',
        password: '<another-pwd>',
        database: '<another-database>',
        synchronize: false,
        entities: ['project2/*.entity.ts'],
        subscribers: ['project2/*.subscriber.ts'],
        migrations: ['project2/migrations/*.ts'],
        cli: { migrationsDir: 'project2/migrations' },
      })
    ]
    

相关问题