Reputation: 1
For some context, I'm building an NodeJS app with FoalTS which uses Express and TypeORM underneath.
My question is around how to implement multiple database connections and accessing them using a single connection by referencing by name.
In my ormconfig.json
file, I have two database connections:
module.exports = [
{
name: 'db1',
type: 'mssql',
database: 'ABC'
...
},
{
name: 'db2',
type: 'mssql',
database: 'XYZ'
...
}
]
And I reference the databases within the Entities:
// reason.entity.ts
@Entity({ database: "ABC" })
export class Reason {
...
// order.entity.ts
@Entity({ database: "XYZ" })
export class Order {
...
However I have an issue where one of the database connections needs to be named "default", otherwise the following error is thrown: ConnectionNotFoundError: Connection "default" was not found.
I found a similar question asked on stack overflow, but the solution to that was aimed more towards NestJS.
I tried renaming "db1"
to "default"
in my ormconfig.json
file, but then EVERY entity tries to use the default database connection, even those with @Entity({ database: "XYZ" })
specified.
So, I'm wondering if there is an equivalent solution similar to the one suggested in the stack overflow question, or if I should take a different approach?
Upvotes: 0
Views: 511
Reputation: 1
Perhaps you should have a look to createConnections from typeorm instead of createConnection when the app initialized. Doc createConnection:
Creates a new connection and registers it in the manager. Only one connection from ormconfig will be created (name “default” or connection without name).
Take a look at https://orkhan.gitbook.io/typeorm/docs/multiple-connections
Upvotes: 0