【问题标题】:How can I access database using nestjs/typeorm with database name in multiple databases如何在多个数据库中使用带有数据库名称的 nestjs/typeorm 访问数据库
【发布时间】:2022-07-22 02:00:05
【问题描述】:
const defaultOptions = {
  type: 'postgres',
  port: 5432,
  username: 'user',
  password: 'password',
  database: 'db',
  synchronize: true,
};

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...defaultOptions,
      host: 'user_db_host',
      entities: [User],
    }),
    TypeOrmModule.forRoot({
      ...defaultOptions,
      name: 'albumsConnection1',
      host: 'album_db_host',
      entities: [Album],
    }),
    TypeOrmModule.forRoot({
      ...defaultOptions,
      name: 'albumsConnection2',
      host: 'album_db_host',
      entities: [Album],
    }),
    ...
  ],
})
export class AppModule {}

嗨, 我想发送一个名称参数来访问名称的数据库并获取查询结果。

例如,当我发送一个

{ dbname: 'albumsConnection1' }

如何使用参数 dbname 访问特定数据库?

【问题讨论】:

    标签: express nestjs typeorm


    【解决方案1】:

    如果您想使用上面定义的数据库之一在您的服务中运行原始查询,请使用@InjectConnection() 注入连接,并将连接名称作为其参数:

    import { Connection } from 'typeorm';
    import { InjectConnection } from '@nestjs/typeorm';
    
    @Injectable()
    export class FooService {
      constructor(@InjectConnection('albumsConnection1') private connection: Connection) {}
    
      async doSomeQuery() {
        return this.connection.query('<SOME QUERY>');  // This query will be executed on database 'albumsConnection1'
      }
    }
    

    【讨论】:

    • 我有一个问题,如果我有30个数据库,我必须创建连接注入?
    【解决方案2】:
    import { InjectConnection } from '@nestjs/typeorm';
    import { DataSource, getConnection } from 'typeorm';
    
    @Injectable()
    export class FooService{
       constructor(
        @InjectConnection('NameConnection1')
        private dataSource1: DataSource,
        @InjectConnection('NameConnection2')
        private dataSource2: DataSource,
      ) {}
      async doSomeQuery(connection: string) {
        switch (connection){
          case 'Connection1': this.dataSource1.manager.findOne()
        ...
       }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 1970-01-01
      • 2018-02-20
      • 2019-05-09
      • 2020-04-25
      • 2021-12-06
      • 2020-07-03
      • 2019-11-15
      • 2013-02-27
      相关资源
      最近更新 更多