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.

Daniel Higueras
  • 2,404
  • 22
  • 34
RSKMR
  • 1,812
  • 5
  • 32
  • 73

1 Answers1

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

Community
  • 1
  • 1
A.Z.
  • 1,638
  • 2
  • 18
  • 27
  • 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 ? – gauravmehla Aug 21 '18 at 11:56
  • So how to I split write and read operations per data source? I want to use postgresql cluster – holms Jul 04 '19 at 21:25
  • https://stackoverflow.com/questions/57261932/can-not-created-the-datasource-with-mysql –  Jul 30 '19 at 00:35
  • please check this question –  Jul 30 '19 at 00:36