NestJS-如何在主应用程序模块文件中使用.env变量进行数据库连接 [英] NestJS - How to use .env variables in main app module file for database connection
问题描述
我正在开发我的第一个NestJS应用程序,该应用程序在 app.module.ts
中的硬编码数据库连接字符串上工作正常。
I am working on my first NestJS application, which was working fine with hardcoded database connecting string in app.module.ts
.
但是根据我们的要求,我不得不从环境文件中选择数据库配置值。为此,我遵循了nestjs文档网站上的配置文档- https://docs.nestjs.com/技术/配置
But then as per our requirements, I had to pick the database config values from environment files. For that, I followed the configuration documentation on the nestjs documentation website - https://docs.nestjs.com/techniques/configuration
但是问题是我需要在同一文件中使用.env变量进行数据库连接,这是失败的。
But the issue is that I need to use the .env variables inside the same file for database connection, which is failing.
这是我的原始代码,效果很好:
Here is my original code that was working fine:
@Module({
imports: [
MongooseModule.forRoot(`mongodb+srv://myusername:mypassword@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),
ProductModule,
CategoryModule,
],
controllers: [
AppController,
HealthCheckController,
],
providers: [AppService, CustomLogger],
})
现在,我想从.env文件中选择那些数据库值,例如 local.env
, dev.env
等,具体取决于在环境上。现在,我的代码无法正常工作:
Now, I wanted to pick those DB values from .env files which are like local.env
, dev.env
etc. depending on the environment. Now, my this code is not working:
@Module({
imports: [
ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }),
MongooseModule.forRoot(`mongodb+srv://${ConfigModule.get('DB_USER')}:${ConfigModule.get('DB_PASS')}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),
ProductModule,
CategoryModule,
],
controllers: [
AppController,
HealthCheckController,
],
providers: [AppService, CustomLogger],
})
推荐答案
1。使用 dotenv
1. Using dotenv
npm install dotenv
在您的 package.json
中添加一些脚本来设置您的环境
Add some scripts to your package.json
to set what env you are in.
"scripts": {
...
"start:local": "NODE_ENV=local npm run start"
"start:dev": "NODE_ENV=dev npm run start"
}
在<$ c $中导入 dotenv
c> main.ts 文件。确保在文件顶部执行该操作。
Import dotenv
in main.ts
file. Make sure you do it at the top of the file.
require('dotenv').config({ path: `../${process.env.NODE_ENV}.env` });
2。使用 env-cmd
2. Using env-cmd
您可以使用 env-cmd
npm软件包。
You can use env-cmd
npm package.
npm install env-cmd
并在 package.json
中添加一些用于不同环境的命令,例如:
And add some commands for different envs in package.json
, for example:
"scripts": {
...
"start:local": "env-cmd -f local.env npm run start"
"start:dev": "env-cmd -f dev.env npm run start"
}
...
现在您可以使用env变量,例如:
Now you can use the env variables, for example:
MongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })
process.env.MONGO_CONNECTION_STRING
这篇关于NestJS-如何在主应用程序模块文件中使用.env变量进行数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!