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 TypeScript namespace does not exist or cannot be located

Currently, I am working on coding in TypeScript. The specific code pertains to an Angular 2 application, but the main focus of my inquiry lies within TypeScript itself. Within my project, there are certain files that contain various models, such as the exa ...

Tips on transferring a child Interface to a parent class

Here is my code snippet: LocationController.ts import {GenericController} from './_genericController'; interface Response { id : number, code: string, name: string, type: string, long: number, lat: number } const fields ...

Issue with TypeScript Generics: The operand on the left side of the arithmetic operation must be of type 'any', 'number', or 'bigint'

I seem to be encountering an error that I can't quite decipher. Even though I've clearly set the type of first as a number, the code still doesn't seem to work properly. Can someone provide insights on how to fix this issue? function divide& ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Gaining entry to specialized assistance through an occasion

Having trouble accessing a custom service from a custom event. Every time the event is fired, the service reference turns out to be null. @Component({ selector: "my-component", template: mySource, legacy: { transclude: true } }) export class myComponent { ...

Setting up a custom PrimeNG theme to match our unique style is a great way to

I am currently using the most recent version of "primeng": "^12.2.0", and I am looking to implement my own custom theme for primeng. Despite searching through numerous blogs, I have yet to find a solution. In an attempt to create my cu ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

Merely using Array.isArray check is insufficient to prompt the TypeScript compiler about a potential array value

I have a method where the type can be an array, but I need to verify that it is not an array before accessing the argument. However, despite my check, I am still encountering the following error (excerpt) on line this.setState({ cuisine });: The type &ap ...

What is the method to cancel an Observable subscription without having a reference to the object of type "Subscription"?

If I were to subscribe to an Observable without an object of type "Subscription," how can I properly unsubscribe from it? For instance, if my code looks something like this: this.subscription = bla ... I know I can easily unsubscribe using the following ...

ERROR TS1086: A declaration of an accessor within an ambient context is not allowed. Accessor for firebaseUiConfig(): NativeFirebaseUIAuthConfig

Trying to create a Single Page Application with Angular/CLI 8. Everything was running smoothly locally until I tried to add Firebase authentication to the app. Upon compiling through Visual Studio Code, I encountered the following error message: ERROR in ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Create Functions to Encapsulate Type Guards

Is it possible to contain a type guard within a function as shown below? function assertArray(value: any): void { if (!Array.isArray(value)) { throw "Not an array" } } // This doesn't work function example1(value: string | []) { a ...

Error in Typescript/React: Unable to access the property 'MaxEmailLength' as it is undefined

I am facing an unusual problem with TypeScript. I have two static classes that are mutually referencing each other and causing issues. Class ValidationHelper (single file) import { ValidationErrors } from '../dictionary/ValidationErrors'; ex ...

What is the correct way to use forwardRef in a dynamic import in Next.js?

I've been trying to incorporate the forwardRef in my code, but I'm facing some difficulties. Can anyone help me out with this? I'm encountering the following errors: Property 'forwardedRef' does not exist on type '{}'. ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

Unable to retrieve rxjs resource

After upgrading to rxjs 5.4.3, I encountered an error in the browser. Despite having "rxjs": "5.4.3" installed in my package.json, I cannot seem to resolve this error message. Here's the content of my ts file: import { Injectable ...

Perplexed by the persistent failure of this Jasmine test accompanied by a vexing "timer in queue" error

I'm attempting to test a function that uses RxJS to broadcast long press events to subscribers. Below is the implementation of the function: export function watchForLongPress(target: HTMLElement) { let timer: number; const notifier = new Subject& ...

Can TypeScript be used to generate a union type that includes all the literal values from an input string array?

Is it feasible to create a function in TypeScript that takes an array of strings and returns a string union? Consider the following example function: function myfn(strs: string[]) { return strs[0]; } If I use this function like: myfn(['a', &a ...