How do I connect TypeORM to multiple databases?

I am faced with the challenge of creating tables in two different databases using TypeORM. Each table is associated with a specific database through the use of the @Entity decorator. However, I encounter an error stating that user x does not have write access to database y.

How can I correctly specify the databases for each entity?

// src/entity/User.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'

@Entity({database: 'db1'})
export class User {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  name: string
}
// src/entity/Movie.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'

@Entity({database: 'db2'})
export class Movie {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  title: string
}

The connections are established with the correct credentials:

// src/index.ts
    await createConnection({
      name: 'connection1',
      host: 'SERVER1',
      username: 'bob',
      password: 'xxx',
      type: 'mssql',
      database: 'db1',
      synchronize: true,
      entities: ['src/entity/**/*.ts'],
      migrations: ['src/migration/**/*.ts'],
      subscribers: ['src/subscriber/**/*.ts'],
      cli: {
        entitiesDir: 'src/entity',
        migrationsDir: 'src/migration',
        subscribersDir: 'src/subscriber',
      },
    })

    await createConnection({
      name: 'connection2',
      host: 'SERVER2',
      username: 'mike',
      password: 'xxx',
      type: 'mssql',
      database: 'db2',
      synchronize: true,
      entities: ['src/entity/**/*.ts'],
      migrations: ['src/migration/**/*.ts'],
      subscribers: ['src/subscriber/**/*.ts'],
      cli: {
        entitiesDir: 'src/entity',
        migrationsDir: 'src/migration',
        subscribersDir: 'src/subscriber',
      },
    })

Decorators play a crucial role as we also utilize type-graphql decorators within our class structure. Interestingly, when the entity decorator is left blank, both tables are created in both databases indicating the correct credentials are used.

A similar issue has been discussed here and assistance has been requested here.

Thank you for your assistance.

Answer №1

After receiving valuable guidance from @Aluan in the comments, I managed to solve this myself. Here are the steps for anyone else encountering a similar issue:

  1. To organize your connections/databases, modify the array entities by assigning each connection/database its own folder and naming the most frequently used connection as default:
// src/index.ts
 await createConnections([
      {
        name: 'default',
        host: 'SERVER1',
        username: 'bob',
        password: 'kiwi',
        type: 'mssql',
        database: 'db1',
        ...
       "synchronize": true,
       "entities": ["src/db1/entity/**/*.ts"],
      },
      {
        name: 'connection2',
        host: 'SERVER2',
        username: 'Mike',
        password: 'carrot',
        type: 'mssql',
        database: 'db2',
        ...
       "synchronize": true,
       "entities": ["src/db2/entity/**/*.ts"],
    ])
  1. Create entity files for each database within their respective folders:
    • src/db1/entity/Fruit.ts > table in db1
    • src/db2/entity/Vegetables.ts > table in db2

By setting "synchronize": true, each table will be automatically created in the corresponding database.

  1. Accessing data from the tables:
  • For the default connection:
import { Fruit } from 'src/db1/entity/Fruit'
  fruits() {
    return Fruit.find()
  }
  • For connections other than default:
import { getRepository } from 'typeorm'
import { Vegetable } from 'src/db2/entity/Vegetable'
  vegetables() {
      return async () => await getRepository(Vegetable).find()
  }

Alternatively,

  async vegetables() {
    return await getRepository(vegetables, 'connection2').find()
  }

I hope these instructions aid others facing similar challenges as I did.

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

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

"Encountering an error when attempting to bind a table name as a parameter in

Encountering an issue with a parametrized query using SQLAlchemy's Text object and receiving an error. Here is a functional example: import sqlalchemy as sqlal from sqlalchemy.sql import text db_table = 'Cars' id_cars = 8 query ...

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...

What is the best way to set an array as the value for an HTML form input?

I am attempting to set the value of an array to an input element in HTML. When I run the following code in my browser console, it works: let between0400am0800am = [1669352400000, 1669438800000]; document.getElementById("time400am800amEveryDay"). ...

"Enhance your Vue 3 experience with a stylish Instagram Feed featuring

Struggling to retrieve the most recent Instagram posts from a feed using Vue 3 and Axios due to Instagram's strict-origin-when-cross-origin policy causing constant blocks. All access tokens are properly configured. The Instagram Basic Display API gui ...

Incorporate loading spinner to enhance search functionality

I am currently using Ajax to search for cities and locations. The search query typically takes around 5 seconds to complete. I would like to know how to add a spinner to indicate the waiting time during the search process. Below is a snippet of the code ...

Collection of components displayed in a row - Bootstrap 4

In order to meet the requirement, the label must be positioned above the input element, and the group consisting of each label and input element should be displayed inline with one another. I have managed to achieve this using the following code snippet, ...

Angular 14 Observables are not triggering resize events

There seems to be an issue here, as the code is not being triggered at all. The console log is not printing and this.width is not changing. constructor(private host: ElementRef, private zone: NgZone) {} public ngOnInit(): void { this.observer = new Re ...

It is not possible to add items to an array

Attempting to retrieve data from the database using the callback method "getAllOrdersByUserId". The output is displayed below: [ TextRow { DishOrderId: 163, BagId: 'BPZDXT68148', DateCreated: 2021-05-27T03:55:05.000Z, Bags: & ...

Navigate back to the previous URL and remove any search parameters using React-router-dom V6

After navigating to a page with certain search parameters, I needed to go back to the previous URL and clear the search params. To achieve this, I utilized the useSearchParams function provided by react-router-dom v6. Within the useEffect hook, I implemen ...

Modifying the menu with Angular 4 using the loggedInMethod

Struggling to find a solution to this issue, I've spent hours searching online without success. The challenge at hand involves updating the menu item in my navigation bar template to display either "login" or "logout" based on the user's current ...

Getting MySQL select query values into a PHP variable: A concise guide

Can anyone assist me with using MySQL fetch to avoid receiving a resource ID in my variable? I've read tutorials that use loops, but I'm looking for a way to select only one string into a variable. This is the code I currently have: $img = mysql ...

Is it possible to use an input value to rotate an element?

I'm attempting to rotate a red circle with the ID of outer using Input[type=range]. I've tried selecting the circle's style, then transforming it based on the input value, but it needs to be within the parentheses of rotateZ(), which require ...

Vue3: Pinia store data not being received

Having trouble retrieving Pinia data using the Composition API after a page reload? I'm utilizing Vue to parse fetched JSON data. Despite being new to the Composition API, I can't pinpoint what's causing the issue even after going through th ...

Is there a way to invoke a method on an object stored in an array index?

Attempting to generate infowindows for markers within a Google Map, I utilized an array to create "disposable objects" within a for loop. Unfortunately, my approach is not yielding the desired results. Clicking on the markers has no effect, and upon checki ...

The columnFilter plugin in Datatables is failing to initialize

I have a pre-existing table that needs to be customized and initialized properly. <table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table"> <thead> <tr> <th style="width: 10px;" ...

Ways to apply Position Fixed to a particular Div element and subsequently eliminate that class while scrolling

Check out my current Jsfiddle project here I am working on a task that involves adding a class to a specific div when scrolling and then removing that class. Below is the JavaScript code I have written for this functionality: var targetDiv = $(".mainwra ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

Struggling to populate dropdown with values from array of objects

My issue is related to displaying mock data in a dropdown using the SUIR dropdown component. mock.onGet("/slotIds").reply(200, { data: { slotIds: [{ id: 1 }, { id: 2 }, { id: 3 }] } }); I'm fetching and updating state with the data: const ...

Calculate the mean value of each array, and then determine which average is higher

After running the code snippet provided, I noticed that it outputs "first" instead of "second". Can you help me verify my logic here? I first calculate both averages and then compare them to return the greater one. Do you see any issues with this approac ...