Reputation: 185
So my question described in topic. I have 2 postgres dbs hosted by docker and service with Nest.js. Also I use knex + objection.js. I spent about 2 hours searching this on google and found nothing compared to my stack
For now I connect 1 db like this:
const customProviders = [
{
provide: 'KnexConnection',
useFactory: async (config: Config) => {
const connection = knex(config.db);
await connection.migrate.latest();
Model.knex(connection);
return connection;
},
inject: [Config]
}
];
Upvotes: 1
Views: 1637
Reputation: 19718
Create 2 separate knex
instances. One for connecting each database.
You can then choose for every query to which database query should be sent with Model.query(dbConnection)...
or you can create 2 sets of models, which are bound to different databases with https://vincit.github.io/objection.js/api/model/static-methods.html#static-bindknex.
Basically you can do
const PersonBoundToDb1 = Person.bindKnex(db1);
const PersonBoundToDb2 = Person.bindKnex(db2);
// this query goes to db1
await PersonBoundToDb1.query()...;
// this query goes to db2
await PersonBoundToDb2.query()...;
More info how to use multitenant databases with objection.js is found here https://vincit.github.io/objection.js/recipes/multitenancy-using-multiple-databases.html#model-binding-pattern
Upvotes: 1