TypeORM does not have the capability to specify the database setting within the entity decorator

As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations.

To achieve this, I have been experimenting with the database setting on the @Entity decorator, following the guidelines provided at:

In order to test this approach, I created a simple example with two entities that should ideally reside in different databases:

@Entity({ database: 'test' })
export default class Entity1 {
    @PrimaryGeneratedColumn()
    id?: number

    @Column()
    name?: string

    @Column()
    address?: string
}

and

@Entity({ database: 'database2' })
export default class Entity2 {
    @PrimaryGeneratedColumn()
    id?: number

    @Column()
    name?: string

    @Column()
    address?: string
}

The code snippet below initializes the database connections:

import {createConnections} from "typeorm";

async function doDbExample() {
    const connections = await createConnections([{
        name: "db1Connection",
        type: "postgres",
        host: "db",
        port: 5432,
        username: "test",
        password: "testPassword",
        database: "test",
        entities: [__dirname + "/entity/*{.js,.ts}"],
        synchronize: true
    }]);

    console.log("Created connections")
}

doDbExample()

However, despite specifying the database for each entity, both tables end up in the same database of the connection. This behavior raises the question of whether I am missing something or encountering a bug in TypeORM where the database setting is not being respected as expected.

I am executing the code using ts-node-dev.

For a comprehensive reproducible example, including a Dockerized setup of the database environment, please refer to the repository on GitHub: https://github.com/petterroea/TypeOrmBug-MRE

Answer №1

This challenge was related to setting up multiple connections and databases in my project. Here's how I tackled it:

  1. To organize the entities, I made sure each connection/database had its own folder with entity files. The most frequently used entity was named 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. I created separate entity files for each database in their respective folders:
    • src/db1/entity/Fruit.ts > table in db1
    • src/db2/entity/Vegetables.ts > table in db2

By using "synchronize": true, tables were automatically created in the appropriate database.

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

or

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

I hope this solution can assist others facing similar challenges in managing database connections effectively.

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

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Issues with TypeScript arise when transferring arguments between functions

Encountering a TypeScript error due to this pattern: Error message: 'Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]' function foo(value: string | number) { return bar([va ...

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

difficulties arise when trying to use ngOnChanges to update an array

My code includes an array that is being updated from another component, with new Strings being added to it using the array.push() method. I have verified this update by testing it with a button, however, ngOnChanges does not seem to detect any change in ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Switching Theme Dynamically in a Multi-tenant Next.js + Tailwind App

I'm currently developing a Next.js + Tailwind application that supports multiple tenants and allows each tenant to easily switch styles or themes. I've been struggling with the idea of how to implement this feature without requiring a rebuild of ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

I am unable to access the object property in Typescript

Here is an object definition: const parsers = { belgianMobile: (input: string) => input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '), }; Now, I want ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

Efficient Typescript ambient modules using shorthand notation

Exploring the code snippet from the official module guide, we see: import x, {y} from "hot-new-module"; x(y); This syntax raises a question: why is 'x' not within curly brackets? What does this coding structure signify? ...

No interface 'JSX.IntrinsicElements' could be found, causing the JSX element to be implicitly of type 'any'

<Header> <title>Real Estate API Application</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, ...

What sets apart using (@Inject(Http) http: Http) from not using it?

Following a recent query, I now have a new question. What sets apart these two approaches? Here is the original code I used: import {Http, HTTP_PROVIDERS} from 'angular2/http'; @Component({ viewProviders: [HTTP_PROVIDERS], ..// constructor(h ...

Is there a way to help my KafkaJS consumer stay patient while waiting for a broker to become available?

My KafkaJS consumer setup looks like this: // Create the kafka client const kafka = new Kafka({ clientId, brokers, }); // Create the consumer const consumer = this.kafka.consumer({ groupId, heartbeatInterval: 3000, sessionTimeout: 30000, }); // ...

Finding the key type in an interface

Here is a challenge... This is the code snippet from titleBarContainer.tsx: function TitleBarContainer() { const systemData = useSelector((state: RootState) => state.counter.systemData) const dispatch = useDispatch() const onChangeSystemDa ...

Utilizing a string variable as a property name for dynamic typing

I am looking to dynamically create a type with a property name based on specified parameters. Although I can successfully create the object, I am facing challenges when trying to create the actual type. This dynamic type creation is essential for compositi ...

Creating a type that can be used with a generic type T along with an array of the same generic type T

I am experimenting with TypeScript for this project type ArrayOrSingleType<T> = T | T[]; interface TestType<T> { a: ArrayOrSingleType<T>; b: (v: ArrayOrSingleType<T>) => void; } const testVariable: TestType<number&g ...

Understanding the concept of mutable properties in Typescript

Why can the property 'name' in the class 'PersonImpl' be reassigned even though it is not declared as read-only in the Person interface? interface Person { readonly name: string; } interface Greeting extends Person { greet( ...