Loopback + connect multiple database
Asked Answered
I

1

8

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.

Inferential answered 9/2, 2016 at 7:52 Comment(0)
S
4

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

Slag answered 9/2, 2016 at 11:52 Comment(4)
What will happen if I am switching database for each request i.e I have prod, test, dev, stag databases and I want to keep one API server which is connected to these data sources ?Associative
So how to I split write and read operations per data source? I want to use postgresql clusterMonseigneur
#57262432Charged
please check this questionCharged

© 2022 - 2024 — McMap. All rights reserved.