Francesco Borzi
Francesco Borzi

Reputation: 61994

NestJS + MySQL: how to connect to multiple databases without setting entities

The NestJS documentation about Databases explains how to connect to MySQL using TypeORM and defining Entities.

In my case, I have to connect to an MySQL server that has more than one database and I need to execute SQL queries directly (without using the Entity layer) and fetch their results. Sometimes I also need to run cross-database queries.

How to do that using NestJS?

Upvotes: 2

Views: 5548

Answers (1)

Kim Kern
Kim Kern

Reputation: 60517

You can import multiple databases by given the connections different names. You can either directly pass the database configuration in separate TypeOrmModule.forRoot({...}) imports or use a ormconfig.json config file. (However, the ormconfig.json file might still not work with multiple databases, see this thread.)

TypeOrmModule.forRoot({
  ...defaultOptions,
  name: 'personsConnection',
  ^^^^^^^^^^^^^^^^^^^^^^^^^^
  host:  'person_db_host',
  entities: [Person],
}),
TypeOrmModule.forRoot({
  ...defaultOptions,
  name: 'albumsConnection',
  ^^^^^^^^^^^^^^^^^^^^^^^^^
  host:  'album_db_host',
  // You can also leave the entities empty
  entities: [],
})

As stated by Kamil in the comments, you can inject the TypeORM connection object with @InjectConnection('albumsConnection'): Connection and then use the QueryBuilder or the method query to run raw SQL.

const rawData = await connection.query(`SELECT * FROM USERS`);

Upvotes: 4

Related Questions