Jackson Harry
Jackson Harry

Reputation: 323

How to use multiple database connection with one model dynamically in sailsjs?

I am beginner in sailsjs, i have multiple databases but table structure is same. So i would like to use single model and controller for all these databases.

I know we can set connection attribute in model like this

module.exports = {
    connection: 'mysqlServer1',
    attributes: {
    userid: {
        type: 'integer',
        primaryKey: true
    },
    fbid: {
        type: 'string'
    },
    source: {
        type: 'string'
    }
   }    
 }
};

But how can we set connection dynamically runtime?

Thanks

Upvotes: 1

Views: 632

Answers (2)

wwwslinger
wwwslinger

Reputation: 986

I know this is old, but I stumbled on it looking for a solution to different problem, thought I'd answer.

The simplest way is to just set environment variables and use defaults.

For example, if you put MODELA_CONN="mysqlServer1" in your .bash_profile, or lift sails with an export like export MODELA_CONN="mysqlServer1" && sails lift, then you can just use that:

module.exports = {
  connection: process.env.MODELA_CONN || "defaultMysql",
  ...
}

Upvotes: 1

Jordi
Jordi

Reputation: 36

I am afraid this isn't possible yet. The closest thing you can get to a dynamic connection is using the following npm package https://github.com/sgress454/sails-hook-autoreload. This will automatically reload sailjs with the changed connection config, without to lift sails again. But it won't cover your problem during runtime.

Upvotes: 0

Related Questions