Connecting to Atlas
Connecting to Atlas means using the mongodb+srv connection string from your cluster, kept in an environment variable.
In this page:
Syntax
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
// .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
- Committing the connection string
- Forgetting to whitelist your IP
- 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: