使用环境变量进行本地 sequelize 配置

using an enviroment variable for local sequelize configuration(使用环境变量进行本地 sequelize 配置)

本文介绍了使用环境变量进行本地 sequelize 配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 sequelize 在我的项目的 config.json 文件中使用环境变量.我正在使用 dotenv 在本地设置环境变量.我的 config.json 文件是这样的

I'm looking to use an environment variable inside of the config.json file of my project using sequelize. I'm using dotenv to set environment variables locally. My config.json file looks like this

{
  "development": {
    "username": process.env.DB_USER,
    "password": process.env.DB_PASS,
    "database": process.env.DB_DATABASE,
    "host": process.env.DB_HOST,
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "use_env_variable": "JAWSDB_URL",
    "dialect": "mysql"
  }
}

我遇到的问题是我无法在 config.json 文件中使用变量.看起来我可以使用use_env_varable"键并将env变量用于我的连接字符串.所以我想我要么需要一种方法来找出我的本地 mysql 数据库的组合连接字符串,要么需要一种在 config.json 中使用变量的方法.有什么解决办法吗?

The issue I'm having is that I can't use variables inside the config.json file. It looks like for production I can use the "use_env_varable" key and use the env variable for my connection string. So I guess I either need a way to figure out the combined connection string for my local mysql db or a way to use variables inside the config.json. Any solutions?

推荐答案

你应该将 config.json 文件更改为 config.js 模块,并确保 >需要最顶部的dotenv.

you should change config.json file to a config.js module and make sure to require the dotenv at the very top.

require('dotenv').config(); // this is important!
module.exports = {
"development": {
    "username": process.env.DB_USERNAME,
    "password": process.env.DB_PASSWORD,
    "database": process.env.DB_DATABASE,
    "host": process.env.DB_HOST,
    "dialect": "mysql"
},
"test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
},
"production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql"
}
};

注意:更新您的 .sequelizerc 文件以匹配新的配置文件.

NOTE: update your .sequelizerc file to match the new config file.

"config": path.resolve('./config', 'config.js'),

这篇关于使用环境变量进行本地 sequelize 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用环境变量进行本地 sequelize 配置

基础教程推荐