How to define two MySQL database connections in Sails.js

孤街醉人 提交于 2020-01-01 11:36:33

问题


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


回答1:


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'
};


来源:https://stackoverflow.com/questions/24776174/how-to-define-two-mysql-database-connections-in-sails-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!