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.
有多种方法可以将环境变量从文件加载到脚本。此示例使用内置的loadEnvFile() 函数,该函数将变量从 .env文件加载到应用程序的环境中。
步骤
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对象访问连接字符串环境变量。