Instructor: Let's create a new project named Foo. In there, let's create a simple Node.js script that connects to a locally running MongoDB instance. We'll install the MongoDB module with Yarn, and then start our script with Node. We can see that we can successfully connect to our MongoDB instance.
The current configuration doesn't allow for the connection string to be changed on the fly. Moving configuration values into environment variables has many benefits. Let's go ahead and copy the connection string, and replace it with a reference to our environment variable.
Environment variables are referenced by process.env, followed by the name of our environment variable in caps. In this case, we'll name it Mongo_URI. Let's save our file. We'll start the Node script again, but this time prepend the command with our new environment variable.
We can see that we can still connect to the database, but our connection string is moved out of code and into the environment. If you have many environment variables or want an easier way to start your script, you can create a new .env file and move your environment variables there.
To inject our external environment file into our Node.js script, we'll need a package called .env. Let's add it with Yarn. Next, we'll require this module at the top of our script, immediately invoking the config function. This function will automatically look for a file named .env, and inject the values contained within this file into the environment.
Let's go back and start our Node process directly now, and see that we are still connecting to the MongoDB instance from the values within our environment file.