← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 5 of 7

Connecting to Atlas

Connecting to Atlas means using the mongodb+srv connection string from your cluster, kept in an environment variable.

In this page:

  1. Connecting to Atlas
Syntax
javascript
await mongoose.connect("mongodb+srv://username:[email protected]/database");

Connecting to Atlas

Copy the connection string from the Atlas Connect dialog, substitute the database user's password and default database, and store it in MONGODB_URI.

Ensure your IP is allowed in Network Access. Options such as serverSelectionTimeoutMS help fail fast when the cluster is unreachable.

Note: URL-encode special characters in the password.

Example: Connecting to Atlas

javascript
// .env
// MONGODB_URI=mongodb+srv://appUser:p%[email protected]/shop?retryWrites=true&w=majority

require("dotenv").config();
const mongoose = require("mongoose");

mongoose.connect(process.env.MONGODB_URI, { serverSelectionTimeoutMS: 5000 })
  .then(() => console.log("Connected to Atlas"))
  .catch((err) => { console.error("Connection failed:", err.message); process.exit(1); });

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Committing the connection string
  2. Forgetting to whitelist your IP
  3. Not encoding special password characters
Chapter Summary
  • Use the mongodb+srv string
  • Keep it in an environment variable
  • Allow your IP in Atlas
  • Set timeouts to fail fast
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.