'How can I access database using nestjs/typeorm with database name in multiple databases

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 {}

Hi, I want to send a name parameter to access the DB of the name and get the results for the query.

For example, when I send a

{ dbname: 'albumsConnection1' }

How can I access specific database with parameter dbname?



Solution 1:[1]

If you want to run a raw query in your service with one of the databases defined above, inject the connection using @InjectConnection() with connection name as its parameter:

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'
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kien Nguyen