You can use environment variables in your MongoDB Shell scripts to manage configuration settings and store sensitive information outside of your source code. For example, environment variables let you store database connection strings, API keys, and other parameters outside of your main scripts.您可以在MongoDB Shell脚本中使用环境变量来管理配置设置,并将敏感信息存储在源代码之外。例如,环境变量允许您在主脚本之外存储数据库连接字符串、API键和其他参数。
About this Task关于此任务
In the following example, you will learn how to use an environment variable for your MongoDB connection string.在以下示例中,您将学习如何为MongoDB连接字符串使用环境变量。
There are multiple ways to load environment variables from a file into your script. This example uses the built-in 有多种方法可以将环境变量从文件加载到脚本中。此示例使用内置的loadEnvFile() function, which loads variables from an .env file into your application's environment.loadEnvFile()函数,该函数将变量从.env文件加载到应用程序的环境中。
Steps步骤
Create a file to store your environment variable创建一个文件来存储环境变量
In an empty directory, create a new file named 在一个空目录中,创建一个名为.env..env的新文件。
Define an environment variable定义环境变量
In the 在.env file, define an environment variable for your MongoDB connection string:.env文件中,为MongoDB连接字符串定义一个环境变量:
MONGODB_URI="<connection-string>"Write a script that uses the environment variable编写一个使用环境变量的脚本
In the same directory as your 在与.env file, create a script called myScript.js and populate it with the following contents:.env文件相同的目录中,创建一个名为myScript.js的脚本,并用以下内容填充它:
// Load environment variables from the .env file从.env文件加载环境变量
const { loadEnvFile } = require('node:process');
loadEnvFile();
// Connect to the MongoDB database连接到MongoDB数据库
db = connect(process.env.MONGODB_URI);
// Confirm the connection by printing the database name通过打印数据库名称确认连接
console.log(db);
The script uses the 该脚本使用process.env object to access your connection string environment variable.process.env对象访问连接字符串环境变量。