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:
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.
Nothing new here, but how can we tell objectionjs to give our models a specific database connection?
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.
Now we can execute our application
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.
and you can see our app has generated two connections for each database.
That’s it! 🚀