Skip to Content
Lesson 2

MongoDB Atlas & Connecting an App

Workplace Context

Your team is developing a new Node.js application that requires a database. Instead of hosting the database on-premise, the decision has been made to use a cloud-hosted solution for better scalability and reliability. Your task is to set up a new MongoDB database on Atlas, connect it to the application, and ensure the connection credentials are kept secure.


Learning Objectives

By the end of this lesson, you will be able to:

  • Set up a new MongoDB cluster on MongoDB Atlas.
  • Connect a Node.js application to a MongoDB database using a connection string.
  • Secure database credentials using environment variables.

What is MongoDB Atlas?

MongoDB Atlas is a fully-managed, cloud-based database service for MongoDB. It handles all the complexity of deploying, managing, and scaling your database, allowing you to focus on building your application.

Key features include:

  • Automated Provisioning and Scaling: Easily scale your database up or down with a few clicks.
  • High Availability: Atlas distributes your database across multiple servers (a “cluster”) to ensure it’s always available.
  • Security: Provides multiple layers of security, including network isolation, access control, and end-to-end encryption.
  • Monitoring and Backups: Comes with built-in tools for monitoring performance and scheduling automatic backups.


Connecting Your Application

To connect your Node.js application to your Atlas cluster, you need two things:

  1. A MongoDB Driver: This is a library for your programming language that knows how to communicate with a MongoDB database. For Node.js, the official driver is the mongodb package.
  2. A Connection String: This is a special URL that contains all the information the driver needs to connect to your database, including the address of the cluster, the database name, and your credentials.

Installing the MongoDB Driver

First, you need to install the mongodb package from npm.

npm install mongodb

Aside: ODMs

While we will use the MongoDB driver directly for the first few examples you will come across, you should know that many developers prefer to use an Object Data Modeling (ODM) library to interact with their databases. The most popular ODM for MongoDB is called Mongoose.

We will get started with Mongoose very soon, so don’t worry if you don’t internalize the basic MongoDB driver syntax just yet!

Getting Your Connection String

You can get your connection string from the MongoDB Atlas dashboard. When you create a new cluster, Atlas will guide you through creating a database user and whitelisting IP addresses that are allowed to connect. At the end of this process, it will provide you with a connection string that looks something like this:

mongodb+srv://<username>:<password>@cluster0.abcde.mongodb.net/?retryWrites=true&w=majority

You must replace <username> and <password> with the actual credentials for the database user you created.

Example: Connecting to MongoDB

Here is a basic example of how to connect to a MongoDB database from a Node.js script.

index.js
const { MongoClient } = require('mongodb'); // Replace this with your own connection string const uri = "..."; const client = new MongoClient(uri); async function run() { try { // Connect the client to the server await client.connect(); // Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to MongoDB!"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Note

When you build your own applications, you will need to use the connection string provided by your own MongoDB Atlas cluster.


Securing Credentials with Environment Variables

You should never hard-code your connection string directly into your source code (like we did above!). If you do, anyone who sees your code (for example, if you publish it to a public GitHub repository) will have your database username and password.

The standard practice is to store sensitive information like this in environment variables. Environment variables are variables that are set in the operating system, outside of your application code.

To make working with environment variables easier in development, we can use the dotenv package. This package loads variables from a special file named .env into the Node.js process.env object.

  1. Install dotenv:

    npm install dotenv
  2. Create a .env file:

    Create a new file named .env in the root of your project. This file should never be committed to version control.

    .env
    MONGO_URI="mongodb+srv://your_username:your_password@cluster0.abcde.mongodb.net/your_database_name"
  3. Add .env to .gitignore:

    Make sure your .env file is not tracked by Git by adding it to your .gitignore file.

    .gitignore
    node_modules .env
  4. Load and use the variables in your code:

    At the very top of your application’s entry point (e.g., index.js), require and configure dotenv.

    index.js
    require('dotenv').config(); const { MongoClient } = require('mongodb'); // The connection string is now loaded from your .env file const uri = process.env.MONGO_URI; const client = new MongoClient(uri); async function run() { // ... (rest of the connection logic) } run().catch(console.dir);

Now, your application can connect to the database without exposing any credentials in the source code.


Activities

Activity 1: Set Up a MongoDB Atlas Cluster

  1. Sign up for a free MongoDB Atlas account.
  2. Create a new project and build a new cluster. Choose the free “M0” tier for this activity.
  3. Create a new database user with a secure password. Remember to save the password somewhere safe.
  4. Configure network access. For development purposes, you can add your current IP address to the whitelist, or whitelist all IP addresses.
  5. From the “Connect” dialog, copy the connection string for your cluster.

Activity 2: Connect Your Node.js App

  1. Initialize a new Node.js project (npm init -y).
  2. Install the mongodb and dotenv packages.
  3. Create a .env file and add your Atlas connection string to it as MONGO_URI. Remember to replace <password> with your actual password.
  4. Create a .gitignore file and add .env and node_modules to it.
  5. Create an index.js file that requires dotenv, reads the connection string from process.env, and uses it to connect to your database.
  6. Run the script (node index.js). If successful, you should see a confirmation message in your console.

Knowledge Check

Why is it a bad practice to hard-code your database connection string in your source code?

  • Select an answer to view feedback.

What is the purpose of the .env file?

  • Select an answer to view feedback.

Which command should you use to install the official MongoDB driver for Node.js?

  • Select an answer to view feedback.

Summary

In this lesson, you learned how to set up a cloud-hosted database using MongoDB Atlas. You saw how to connect a Node.js application to your database using the official MongoDB driver and a connection string. Most importantly, you learned the critical practice of securing your database credentials using environment variables with the dotenv package. This ensures your application is both functional and secure.


References


Additional Resources