Multiple database connections in objectionjs and knex
Normally you have one database for your app, but when your app starts to grow
it’s normal to create more databases to handle more traffic in an efficient way.
So the question is:
Is objectionjs ready for this?
Spoiler Alert: YES.
Let’s assume we have 2 databases called: db_one and db_two
and what we want to achieve is to connect one of our objectionjs Models to the database db_one and the other one to the database db_two.
Let’s start creating our models.
1 | // models/Product.js |
Nothing new here, but how can we tell objectionjs to give our models a specific database connection?
Introducing bindKnex
Every objectionjs model has this method called bindKnex and it accepts one parameter: a valid knexjs database connection. And it will return the same model, but binded to a knexjs connection.
Let’s see the code to have a better understanding of it.
1 | // index.js |
Now we can execute our application
1 | node index.js |
and each model will make a query to a different database.
We can easily check this using the SHOW PROCESSLIST sql query in our mysql terminal.
1 | SHOW PROCESSLIST; |
and you can see our app has generated two connections for each database.
That’s it! 🚀