Connecting to Multiple Databases in NestJS with MySQL Without Defining Entities

If you're interested in learning about connecting to MySQL using TypeORM and defining Entities, the NestJS documentation has all the information you need.

In a situation where you have to connect to a MySQL server with multiple databases and need to execute SQL queries directly (without relying on the Entity layer) to fetch results, it can be challenging. Particularly if you also require running cross-database queries.

So, how can this be achieved using NestJS? Let's find out!

Answer №1

To incorporate multiple databases, assign different names to each connection. You can achieve this by passing the database configuration directly in separate TypeOrmModule.forRoot({...}) imports or by utilizing a ormconfig.json config file. (However, please note that the ormconfig.json file may not fully support multiple databases as discussed in 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: [],
})

According to Kamil's comment, you can inject the TypeORM connection object with

@InjectConnection('albumsConnection'): Connection
and then utilize the QueryBuilder or the method query to execute raw SQL queries.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up Angular Toolkit via npm installation

After successfully installing the UIKit npm package within an Angular 2 CLI project, what steps should I take to utilize it? I have also installed typings for UIKit (@types/uikit), but I am unsure of how to properly import the package into a controller i ...

Implementing the binding of components to another component post using forwardRef

I am looking to connect the Title and Body components with the Wrapper component. Previously, my component structure looked like this: import { FC } from 'react'; // binding required components const Title: FC<...> = () => {...} const ...

Modifying the form-data key for file uploads in ng2-file-upload

I have implemented the following code for file upload in Angular 2+: upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a f ...

How to Retrieve Data from an HTML Table using the Laravel Framework

I have a unique and interactive Dynamic Sortable Table where I can effortlessly add or delete rows likethis uploaded image here. There is an intriguing loop in my controller that runs precisely 4 times, based on the number of columns in the table. However, ...

Is a custom test required for PartiallyRequired<SomeType>?

Is there a way to create a function that validates specific fields as required on a particular type? The IFinancingModel includes the property statusDetails, which could potentially be undefined in a valid financing scenario, making the use of Required< ...

Mapping a response object to a Type interface with multiple Type Interfaces in Angular 7: A step-by-step guide

Here is the interface structure I am working with: export interface ObjLookup { owner?: IObjOwner; contacts?: IOwnerContacts[]; location?: IOwnerLocation; } This includes the following interfaces as well: export interface IObjOwner { las ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

Angular: How to Resolve Validation Error Messages

I have a TypeScript code block: dataxForm: fromGroup this.dataxForm = new FormGroup({ 'Description':new FormControl(null, Validaros.required}; 'Name':new FormControl(null, Validators.required}) Here is an HTML snippet: <mat-divider& ...

Breaking up React code within the React.createElement() function

I am encountering an issue with lazily loaded pages or components that need to be rendered after the main page loads. When using createElement(), I receive the following error: LazyExoticComponent | LazyExoticComponent is not assignable to parameter of ty ...

Utilize variable as both a function and an instance of a class

Is there a way to access a variable as both a function and an object instance using TypeScript? log("something"); log.info("something"); I've attempted various methods, such as modifying the prototype, but nothing has proven succ ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

MySQL's "For Each" feature allows for iterating over each element in a

I am currently developing a website for code questions, similar to the platform CodeChef. At the moment, my database includes two tables: problems and submissions. The problems table contains a single field called id, which is set to auto_increment. (The ...

Guide on switching DELETE_RULE to CASCADE for all tables

My attempted solution included: use information_schema update referential_constraints set delete_rule='cascade'; However, this resulted in the following error message: ERROR 1044 (42000): Access denied for user 'root'@'localho ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

What happens when you encounter a blank page while using mysqli_query()?

My new project involves creating a song recommendation website, and I've set up a form that directs to a page containing the following code: <?php ini_set('display_errors',1); ob_start(); session_start(); ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

The error message "result.subscribe is not a function" indicates that there was a problem

I encountered an issue with the following error message: Uncaught TypeError: result.subscribe is not a function Here's a screenshot of the error for reference: https://i.sstatic.net/yfhy0.png Despite attempting to handle the error, I'm still s ...