Handling database environment configuration in Sai

2019-02-05 03:17发布

问题:

The issue I have is related to the following quote from the 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.

How can you configure the connection for a production server?

My connections.js file looks like this:

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

And in my environment config files I've got:

development.js

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

production.js

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

This works on my local machine, because the production database server is on an external server. On the production environment I'm getting the following error:

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

It works if I remove the mongoDev object from my the connections object.

I've also tried using adaptors.js, but this only resulted in some deprecation errors.

$ sails -v
info: v0.9.9

I'm getting something different when running sails lift:

info:    Sails         
info:    v0.10.5

回答1:

You want to save the actual connection definition in the either development.js or production.js and remove them from connections.js. It's a little non-intuitive.

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