This content originally appeared on DEV Community and was authored by Abdelhakim mohamed
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):
-
Import the MongoDB public GPG key:
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
-
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
-
Reload the local package database:
sudo apt-get update
-
Install MongoDB:
sudo apt-get install -y mongodb-org
-
Start the MongoDB service:
sudo systemctl start mongod
-
Verify installation:
mongo --version
For macOS:
-
Install Homebrew (if not installed):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
-
Use Homebrew to install MongoDB:
brew tap mongodb/brew brew install mongodb-community@6.0
-
Start MongoDB:
brew services start mongodb/brew/mongodb-community
-
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.
-
Initialize a new Node.js project:
npm init -y
-
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();
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
-
Sign Up for MongoDB Atlas:
- Go to MongoDB Atlas and sign up for a free account.
-
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."
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).
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.
-
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.
-
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
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();
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:
-
Install dotenv:
npm install dotenv
-
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
-
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.
This content originally appeared on DEV Community and was authored by Abdelhakim mohamed
Abdelhakim mohamed | Sciencx (2024-09-29T01:24:55+00:00) Connecting MongoDB to a Node.js Application: Locally and Using MongoDB Atlas – Node.js Tutorial – Part 13. Retrieved from https://www.scien.cx/2024/09/29/connecting-mongodb-to-a-node-js-application-locally-and-using-mongodb-atlas-node-js-tutorial-part-13/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.