I am using loopback framework with nodejs.
Is it possible to connect multiple database at a time.
For example I have two different database.
1. Mysql Database - A
2. Postgresql - B
Some pages get data from A database and some pages need get data from B database. could it be possible to do that?
More Details:
Lets say we have two modules.One module interacted with MySQL and another module interacted with postgreSQL.
LoopBack provides connectors for popular relational and NoSQL databases. LoopBack database connectors implement create, retrieve, update, and delete operations as a common set of methods of PersistedModel.
When we talk about LoopBack, we're usually talking about rapid API generation. But behind the REST APIs is a full object-relational mapping (ORM) system that enables you to do all the standard create, read, update, and delete (CRUD) operations in your Node. js code.
You can create multiple datasources inside datasources.json or you can create datasources dynamically. For your particular case you have to install loopback-connector-mysql and loopback-connector-posgresql
datasourcses.json
{
"mysql": {
"name": "mysql",
"connector": "mysql"
},
"postgresql": {
"name": "postgresql",
"connector": "postgresql"
}
}
Don't forget to add host, port, username, password and other properties to setup connection properly.
Next thing to do is to use attachTo() method to change model datasource when you want to switch database.
app.models.YourModel.attachTo(app.dataSources.mysql);
... or ...
app.models.YourModel.attachTo(app.dataSources.postgresql);
Also check this answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With