How to define two MySQL database connections in Sails.js

mysql, sails.js

Solution

Yes, you can define multiple connections and set each model to use a different one. Please see the documentation on connections for a full review.

You can set up as many connections as you need in your config/connections.js file. You can even set up multiple connections using the same adapter:

module.exports.connections = {
  // A MySQL connection
  mysql1: {
    adapter: 'sails-mysql',
    user: 'root',
    host: 'localhost',
    database: 'database1'
  },
  // Another MySQL connection, same server, different database
  mysql2: {
    adapter: 'sails-mysql',
    user: 'root',
    host: 'localhost',
    database: 'database2'
  },
  // A Postgresql connection
  postgres: {
    adapter: 'sails-postgresql',
    user: 'postgres',
    host: 'localhost',
    database: 'mypsqldb'
  }
};

Then in your model class file, specify the connection to use for that model:

module.exports = {
    connection: 'mysql1',
    attributes: {...}
}

To specify the default connection for models, set it in config/models.js:

module.export.models = {
    connection: 'mysql2'
};

Problem

Using sails.js v0.10 rc8, my app had 1 connection to a mysql database and I would liked for a given model that the data are fetched from another database. Is it possible ? If yes, how to acheive this ? Thanks

Original source