DEV Community

Cover image for Connecting MongoDB to a Node.js Application: Locally and Using MongoDB Atlas - Node.js Tutorial - Part 13
Abdelhakim mohamed
Abdelhakim mohamed

Posted on

Connecting MongoDB to a Node.js Application: Locally and Using MongoDB Atlas - Node.js Tutorial - Part 13

Introduction
If you're working with Node.js and need a powerful database to manage your data, MongoDB is a fantastic choice. Whether you're building an app locally or planning to scale it up using MongoDB Atlas in the cloud, connecting your Node.js app to MongoDB is essential.

In this guide, I’ll show you how to connect to MongoDB locally for development and then take it a step further by connecting to a MongoDB Atlas instance. Let’s dive in!.


1. Setting Up MongoDB Locally

Step 1: Install MongoDB Locally

First, you need to install MongoDB on your local machine. MongoDB provides a detailed installation guide on their website:

MongoDB Community Edition Installation

Follow these steps to install MongoDB on Linux and macOS.

For Linux (Ubuntu/Debian-based):

  1. Import the MongoDB public GPG key:

    wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
    
  2. Create a MongoDB list file for apt:

    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
    
  3. Reload the local package database:

    sudo apt-get update
    
  4. Install MongoDB:

    sudo apt-get install -y mongodb-org
    
  5. Start the MongoDB service:

    sudo systemctl start mongod
    
  6. Verify installation:

    mongo --version
    

For macOS:

  1. Install Homebrew (if not installed):

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
  2. Use Homebrew to install MongoDB:

    brew tap mongodb/brew
    brew install mongodb-community@6.0
    
  3. Start MongoDB:

    brew services start mongodb/brew/mongodb-community
    
  4. Verify installation:

    mongo --version
    

Once MongoDB is installed, you’re ready to connect your Node.js app to it locally.


Step 2: Install the MongoDB Node.js Driver

Let’s now create a Node.js project and install the MongoDB driver, which will allow our app to interact with the MongoDB server.

  1. Initialize a new Node.js project:

    npm init -y
    
  2. Install the MongoDB driver:

    npm install mongodb
    

Step 3: Connect to MongoDB Locally

MongoDB should be running on your machine now. Let’s write a script to connect to it using Node.js.

const { MongoClient } = require('mongodb');

async function connectToMongoDB() {
  const uri = 'mongodb://localhost:27017'; // Local MongoDB URI
  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log('Connected to MongoDB locally!');
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
  } finally {
    await client.close();
  }
}

connectToMongoDB();
Enter fullscreen mode Exit fullscreen mode

This connects your app to MongoDB running at localhost:27017, the default MongoDB port.


2. Connecting to MongoDB Atlas

MongoDB Atlas is MongoDB’s fully managed cloud service. It’s ideal for scaling your app when deploying to production. In this section, I’ll show you how to set up MongoDB Atlas and connect it to your Node.js app. To make things clearer, I'll include some helpful screenshots along the way.

Step 1: Set Up MongoDB Atlas

  1. Sign Up for MongoDB Atlas:

  2. Create a Cluster:

    • Once you're logged in, click "Create a Cluster."
    • Select your preferred cloud provider (AWS, GCP, or Azure) and region.
    • Choose the M0 cluster for the free tier.
    • Click "Create Cluster."

Image description

Image description

3 Whitelist Your IP Address:

  • After your cluster is created, go to "Network Access" in the Atlas dashboard.
  • Click "Add IP Address" and whitelist your current IP (or allow access from anywhere).

Image description

Image description

4 Create a MongoDB User:

  • Go to "Database Access" in the Atlas dashboard.
  • Click "Add New Database User."
  • Set a username and password for your MongoDB user.

Image description

  1. Get the Connection String:
    • Once your user is created, click "Connect" next to your cluster.
    • Select "Connect your application" and copy the connection string provided.

Image description

Image description

  • The string will look something like this:

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

Step 2: Install MongoDB Node.js Driver (If Not Done Already)

If you haven’t already installed the MongoDB Node.js driver, run this command:

npm install mongodb
Enter fullscreen mode Exit fullscreen mode

Step 3: Connect Your Node.js App to MongoDB Atlas

Let’s update our Node.js script to use the connection string from MongoDB Atlas.

const { MongoClient } = require('mongodb');

async function connectToMongoDBAtlas() {
  const uri = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/myDatabase?retryWrites=true&w=majority';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log('Connected to MongoDB Atlas!');
  } catch (error) {
    console.error('Error connecting to MongoDB Atlas:', error);
  } finally {
    await client.close();
  }
}

connectToMongoDBAtlas();
Enter fullscreen mode Exit fullscreen mode

Make sure to replace <username>, <password>, and myDatabase with your actual credentials and database name.


Step 4: Secure Your Connection String with Environment Variables

To avoid exposing sensitive information in your code, store your MongoDB URI in a .env file:

  1. Install dotenv:

    npm install dotenv
    
  2. Create a .env file at the root of your project and add your connection string:

    MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/myDatabase?retryWrites=true&w=majority
    
  3. Update your script to load environment variables:

    require('dotenv').config();
    
    const { MongoClient } = require('mongodb');
    
    async function connectToMongoDB() {
      const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
      const client = new MongoClient(uri);
    
      try {
        await client.connect();
        console.log('Connected to MongoDB!');
      } catch (error) {
        console.error('Error connecting to MongoDB:', error);
      } finally {
        await client.close();
      }
    }
    
    connectToMongoDB();
    

With this setup, you can easily switch between local and Atlas MongoDB instances by updating your .env file.

Conclusion

That’s it! 🎉 You've learned how to connect your Node.js app to MongoDB, both locally and with MongoDB Atlas. When developing locally, using MongoDB on your machine is ideal, but when you're ready to deploy and scale, MongoDB Atlas makes it easy to manage your databases in the cloud.

Top comments (0)