node.js - 使用 sequelize 和环境变量连接数据库的 Node 配置文件设置

标签 node.js database configuration environment-variables sequelize.js

我有一个用于连接 DB 的 sequelize 配置文件:

配置/database.js

const config = require('./config');

module.exports = {
  development: {
    username: config.CONFIG.db_user,
    password: config.CONFIG.db_password,
    database: config.CONFIG.db_name,
    host: config.CONFIG.db_host,
    dialect: config.CONFIG.db_dialect,
    port: config.CONFIG.db_port
  },
  test: {
    username: 'test',
    password: 'test',
    database: 'db_test',
    host: 'localhost',
    dialect: 'mysql'
  },
  production: {
    username: config.CONFIG.db_user,
    password: config.CONFIG.db_password,
    database: config.CONFIG.db_name,
    host: config.CONFIG.db_host,
    dialect: config.CONFIG.db_dialect
  }
};

在 sequelize 模型 index.js 文件中,我想通过将 env 变量传递给前一个文件来设置我需要的环境:

模型/index.js
const env = process.env.NODE_ENV || 'development';
const dbConfig = require('../config/database');

const sequelize = new Sequelize(
  dbConfig.test.database,
  dbConfig.test.username,
  dbConfig.test.password, {
    host: dbConfig.test.host,
    dialect: dbConfig.test.dialect,
    port: dbConfig.test.port
  });

现在我手动完成,有没有办法以编程方式完成?感谢您的帮助!

最佳答案

是的,你可以这样做:

module.exports = function () {

    let development = {
    username: 'test',
    password: 'test',
    database: 'db_test',
    host: 'localhost',
    dialect: 'mysql'};

    let production = {
    username: 'test',
    password: 'test',
    database: 'db_test',
    host: 'localhost',
    dialect: 'mysql'
  };


    switch (process.env.NODE_ENV) {
        case 'development':
            return development;

        case 'production':
            return production;

        default:
            return development;
    }
};

您可以在代码中的任何位置访问环境变量,如下所示:
process.env.var_name

关于node.js - 使用 sequelize 和环境变量连接数据库的 Node 配置文件设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610654/

相关文章:

ajax - 文件上传失败

node.js - 如何使用 Typescript 创建 Node.js 模块

node.js - 如何检测 NodeJS 中的文件编码?

python - Django 1.8 错误 : 'NoneType' object is not callable

python - 将 Excel Oracle DB 查询转换为 Python Pandas

configuration - 此工具 API 版本(1.6,协议(protocol)版本 4)不支持指定的 Gradle 安装 (..)

javascript - 如何在 Nest.js 中使用查询参数?

javascript - 在 Sequelize 中查找与来自其他模型的多个(所有)实例关联的实例

c++ - 在 NetBeans 8.0 中的什么位置分配 SDL 2.0.3 目录?

configuration - JBoss 与 IBM MQ 的消息驱动 bean 外部配置