Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loopback + connect multiple database

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.

like image 582
RSKMR Avatar asked Feb 09 '16 07:02

RSKMR


People also ask

What is LoopBack database?

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.

Is LoopBack an ORM?

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.


1 Answers

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

like image 150
A.Z. Avatar answered Sep 22 '22 07:09

A.Z.