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.
关于此任务
In the following example, you will learn how to use an environment variable for your MongoDB connection string.
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.
步骤
3
编写使用环境变量的脚本
在与 .env文件相同的目录中,创建一个名为 myScript.js 的脚本并使用以下内容填充该脚本:
// Load environment variables from the .env file const { loadEnvFile } = require('node:process'); loadEnvFile(); // Connect to the MongoDB database db = connect(process.env.MONGODB_URI); // Confirm the connection by printing the database name console.log(db);
该脚本使用 process.env对象访问权限连接字符串环境变量。