在 Sails.js 中处理数据库环境配置

Handling database environment configuration in Sails.js

我遇到的问题与 official documentation 中的以下引述有关:

Note If any connection to an adapter is used by a model, then all connections to that adapter will be loaded on sails.lift, whether or not models are actually using them. In the example above, if a model was configured to use the localMysql connection, then both localMysql and remoteMysql would attempt to connect at run time. It is therefore good practice to split your connection configurations up by environment and save them to the appropriate environment-specific config files, or else comment out any connections that you don't want active.

如何配置生产服务器的连接?

我的 connections.js 文件如下所示:

module.exports.connections = {

  mongoDev: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    user: 'username',
    password: 'password',
    database: 'database'
  },

  mongoLive: {
    adapter: 'sails-mongo',
    host: 'host.mongolab.com',
    port: 31681,
    user: 'user',
    password: 'password',
    database: 'database'
  }   
};

在我的环境配置文件中,我有:

development.js

module.exports = {
  models: {
    connection: 'mongoDev'
  }    
};

production.js

module.exports = {
  models: {
     connection: 'mongoLive'
  },
  port: 3000,
};

这适用于我的本地计算机,因为生产数据库服务器位于外部服务器上。 在生产环境中,我收到以下错误:

[Error: failed to connect to [localhost:27017]]

如果我从我的连接对象中删除 mongoDev 对象,它就会工作。

我也尝试过使用 adaptors.js,但这只会导致一些弃用错误。

$ sails -v
info: v0.9.9

当 运行 sails lift:

时我得到了一些不同的东西
info:    Sails         
info:    v0.10.5

您想在 development.js 或 production.js 中保存实际的连接定义并从 connections.js 中删除它们。有点不直观。

development.js

module.exports = {
  connections : {
    mongoDev: {
      adapter: 'sails-mongo',
      host: 'localhost',
      port: 27017,
      user: 'username',
      password: 'password',
      database: 'database'
    }
  },
  models: {
    connection: 'mongoDev'
  }    
};

production.js

module.exports = {
  connections : {
    mongoLive: {
      adapter: 'sails-mongo',
      host: 'host.mongolab.com',
      port: 31681,
      user: 'user',
      password: 'password',
      database: 'database'
    } 
  },
  models: {
     connection: 'mongoLive'
  },
  port: 3000,
};