Toggle Sidebar   Previous Lesson Complete and Continue  

  Refactor code

Store Database Credentials As Environment Variables

One more thing we want to do is to move the database credentials from the index.js file to the config/config.env file.

By storing the credentials in the config/config.env file, we can keep all of the important information for our application in one place. This will make it easier to manage and maintain the application over time.

When we start pushing and pulling code via Git later on in this course, we want to exclude those credentials from being visible in those actions. When we start working with Git, we'll add the config.env declaration to a .gitignore file that excludes it from pushes.

This process will limit the chance of your credentials being accidentally revealed to others by limiting only your local machine and the VPS server to having access to them.

Open config/config.env in your coding editor and add this environment variable to it:

MONGO_URI=mongodb+srv://db_username:[email protected]/?retryWrites=true&w=majority


Make sure you add your actual credentials for both the db_username and db_password variables. And then save the file.

Our config.env will look like this:

Save the file. Now we can access our connection string via process.env.MONGO_URI in the code.

Open the /api/index.js file back up in your code editor and update the code to look like the following:

const express = require('express');
const dotenv = require('dotenv');

const mongoose = require("mongoose")

// Load env variables
dotenv.config({ path: './config/config.env' });

const app = express();

// New code
const mongoString = process.env.MONGO_URI

mongoose.set('strictQuery', false);
mongoose.connect(mongoString, () => {
    console.log("Connected to MongoDB");
});
mongoose.connection.on("error", function(error) {
  if (process.env.NODE_ENV === "development") {
    console.log(error)
  }
})


const PORT = process.env.PORT || 3000;

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

After you are finished editing the file, save your changes and restart the application. If everything is working correctly, you should not see any errors and the application should be running smoothly in your terminal, just like it was before you made any changes.

Refactor

Let's make our index file neater and easier to understand by moving the business logic related to MongoDB to another file. To do this, we create a new file called database.js inside the config folder and move all the MongoDB-related code from index.js into this file. This will help make the code easier to understand and maintain.

The database.js file will look like this:

Then we import this database.js using require function method. By moving the MongoDB-related code to a separate file, our index.js file becomes neater, more concise, and easier to understand. This helps to make the code more organized and maintainable.

Save your changes and restart the application. You should not see any errors.

To make our code even more readable, we can rewrite the database file to use async/await instead of callback functions. This will allow us to write the code in a more intuitive and straightforward way. Here's how we can update the database.js file to use async/await:


const mongoose = require("mongoose")
const mongoString = process.env.MONGO_URI
mongoose.set('strictQuery', false);

// New Code
const connectDB = async () => {
    try {
        const conn = await mongoose.connect(mongoString);  
        console.log(`Connected to MongoDB at ${conn.connection.host}`);
    } catch (error) {
        console.error(`Error connecting to MongoDB: ${error.message}`);
    }

};

// mongoose.connection.on("error", function(error) {
//     if (process.env.NODE_ENV === "development") {
//       console.log('error', error)
//     }
// })  

// New Code
module.exports = connectDB;
  

We have assigned a function for connecting the database to the connectDB variable and exported it. To use this function, we just need to import and call it inside index.js file.

Update the index.js file as follows:

Everything should still work as before.

Complete and Continue