Skip to content

Loopback 3.x multiple database connections #658

Open
@ebracci

Description

@ebracci

Hi everyone,

I am current managing a project in which there is a single instance of Loopback application but each Model must have a different datasource based on the current client that is using an application.

E.g.
CLIENT 1
client: jack.it
dbname: jack

CLIENT 2
client: paul.it
dbname: paul

I have a single model defined with a default datasource that is commons for each client, except for the dbName that changes dinamically.

So, for example, I could have a model named model1 that the first time has to execute an operation on db jack and the same model the second time has to execute an operation on db paul.

Now. I have implemented a dsChanger that, based on the clientId it creates a new db if it is not already present in the dbCache of mongodb and return the instance of the new db object, something like that:

var dsChanger = function(self, clienteId){
  if(app.dbsMap){
    let newDb = app.dbsMap[clienteId];
    if(!newDb){
      newDb = app.dbsMap.default;
    }
    return self.db.db(newDb, {noListener: false});
  }
};

I want to modify the collection function to take as second param the db instance, but I don't really like this solution.

What is the best practice to do this (change dinamically the db) without break the connector logic?

Thank you in advance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions