【问题标题】:Set waterline model connection globally without sailsjs在没有sailsjs的情况下全局设置水线模型连接
【发布时间】:2017-04-04 12:30:49
【问题描述】:

我在我的项目中设置了水线,这不是一个风帆项目。我使用的是 0.11.x 版本。如果我在每个模型中设置连接,它就可以完美运行。 (第一个代码块中被注释掉的行)

当我按照文档在每个模型中设置连接时,我的模型工作正常:

Waterline = require('waterline');

module.exports = Waterline.Collection.extend({
  tableName: 'external_resource',
  meta: {
    schemaName: 'intellinotedb'
  },
  // connection: 'myLocalPostgres',
  attributes: {
    id: {
      type: 'integer',
      required: true
    },

但是,我想根据我设置的 NODE_ENV var 将数据库从 test 更改为 local 到 prod。是否有一个地方可以在全球范围内为所有模型执行此操作?我像这样加载所有模型:

models = []
fs.readdirSync(HOMEDIR + '/lib/models/waterline').forEach (file) =>
  models.push(require(HOMEDIR + '/lib/models/waterline/' + file))

class WaterlineORM

  init:(next)=>
    models.forEach (model) ->
      orm.loadCollection(model)

    orm.initialize config, (err, models) =>
      throw err if(err)
      global.models = models.collections
      global.connections = models.connections
      next()

我的连接如下所示:

const diskAdapter = require('sails-disk');
const postgresAdapter = require('sails-postgresql');

module.exports = {
  adapters: {
    'default': diskAdapter,
    disk: diskAdapter,
    postgres: postgresAdapter
  },

  connections: {
    myLocalDisk: {
      adapter: 'disk',
      migrate: 'alter'
    },

    localhost: {
      migrate: 'safe',
      adapter: 'postgres',
      database: 'intellinote',
      host: 'localhost',
      user: 'postgres',
      password: '',
      port: 5432
    }
  },

  defaults: {

  }
};

【问题讨论】:

  • 可以使用变量吗?例如这样的环境变量:connection: process.env.CONNECTION_NAME,
  • 是的。这可能是最好的方法。如果你愿意,我会接受你的回答

标签: node.js sails.js waterline


【解决方案1】:

使用变量。

例如环境变量

connection: process.env.CONNECTION_NAME,

例如配置变量

var config = require('../config');
...
  connection: config.connectionName,

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 2012-11-13
    • 2012-08-28
    • 2017-12-10
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多