2. MongoDB Atlas
1. Atlas Cluster
Walk through of Setting up MongoDB Atlas and then connecting it to MongoDB Compass — step by step.
1.1 Setting up MongoDB Atlas
1. ✅ Create a MongoDB Atlas Account
Go to: https://www.mongodb.com/cloud/atlas
- Click “Start Free”
- Sign up with Google or email
2. ✅ Create a Free Cluster
- After logging in, click “Build a Database”
- Choose “Shared” (Free tier)
- Choose a cloud provider (AWS, Azure, or GCP)
- Pick a region (close to your location)
- Name your cluster (e.g.,
Cluster0
) - Click “Create Cluster” – may take 1-2 minutes
3. ✅ Create a Database User
Once the cluster is created:
- Go to “Database Access” tab (left menu)
- Click “Add New Database User”
- Choose Username (e.g.,
admin
) - Choose Password (e.g.,
password123
) — you’ll use this in Compass - Select Built-in Roles → Read and write to any database
- Click “Add User”
- Choose Username (e.g.,
4. ✅ Allow Your IP Address
Go to “Network Access” tab:
-
Click “Add IP Address”
-
Click “Allow Access from Anywhere” for testing:
0.0.0.0/0(Or click “Add Current IP” if you’re on a known IP)
-
Click “Confirm”
5. ✅ Get the Connection String
- Go to “Clusters”
- Click “Connect”
- Choose “Connect with MongoDB Compass”
- Copy the connection string:
mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/
Replace
<username>
and<password>
with what you created in step 3.
6. ✅ Open MongoDB Compass & Connect
- Open Compass
- Paste the connection string into the connection field
- Hit “Connect”
🚀 You’re in! You’ll see your cluster’s databases and collections.
🎉 You’re All Set!
You can now:
- View documents
- Insert/edit/delete data
- Run queries
- Use it with your Express/Mongoose app (same connection string!)
1.2 Connection String in App
📦 1. Install Dependencies (if you haven’t already)
npm install mongodb mongoose dotenv
🗂️ 2. .env File (Store the Connection String Securely)
Create a .env
file in your project root:
MONGO_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/myDatabase?retryWrites=true&w=majorityPORT=3000
Replace:
<username>
and<password>
with your MongoDB Atlas usermyDatabase
with the name of the DB you want to connect to
📄 3. app.js (or index.js)
const express = require('express');const mongoose = require('mongoose');const dotenv = require('dotenv');
dotenv.config(); // Load environment variables
const app = express();
// Connect to MongoDB Atlasmongoose.connect(process.env.MONGO_URI).then(() => console.log('✅ Connected to MongoDB Atlas')).catch(err => console.error('❌ MongoDB connection error:', err));
// Sample Routeapp.get('/', (req, res) => { res.send('MongoDB Atlas connected!');});
// Start serverconst PORT = process.env.PORT || 3000;app.listen(PORT, () => { console.log(`🚀 Server running on port ${PORT}`);});
▶️ 4. Run Your App
node app.js
You should see:
✅ Connected to MongoDB Atlas🚀 Server running on port 3000
💡 Bonus Tip:
Keep your .env
file out of Git with .gitignore
:
node_modules/.env
1.3 MongoDB in Your App
- 🔌 Atlas DB connection
- 📄 A
User
model - 🧪 Test API routes (
GET
,POST
) - 💬 Sample test queries to try out
🛠️ Project Structure
myapp/│├── .env├── app.js├── models/│ └── User.js└── routes/ └── userRoutes.js
📄 Database URI and Port
MONGO_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/myapp?retryWrites=true&w=majorityPORT=3000
Replace with your Atlas credentials and DB name.
📄 Mongoose Schema
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: Number,}, { timestamps: true });
module.exports = mongoose.model('User', userSchema);
📄 Express Routes
const express = require('express');const router = express.Router();const User = require('../models/User');
// Create a user (POST /api/users)router.post('/', async (req, res) => { try { const user = await User.create(req.body); res.status(201).json(user); } catch (err) { res.status(400).json({ error: err.message }); }});
// Get all users (GET /api/users)router.get('/', async (req, res) => { try { const users = await User.find(); res.json(users); } catch (err) { res.status(500).json({ error: 'Server error' }); }});
// Find a user by email (GET /api/users/email/:email)router.get('/email/:email', async (req, res) => { try { const user = await User.findOne({ email: req.params.email }); if (!user) return res.status(404).json({ message: 'User not found' }); res.json(user); } catch (err) { res.status(500).json({ error: err.message }); }});
// Delete All Usersrouter.delete('/del', async (req, res) => { try { await User.deleteMany({}); res.send('All users deleted'); } catch (err) { res.status(500).send(err.message); }});
// Delete By IDrouter.delete('/del/:id', async (req, res) => { try { const result = await User.findByIdAndDelete(req.params.id); if (!result) return res.status(404).send('User not found'); res.send('User deleted'); } catch (err) { res.status(500).send(err.message); }});
module.exports = router;
📄 Entry Point
const express = require('express');const mongoose = require('mongoose');const dotenv = require('dotenv');
dotenv.config();
const userRoutes = require('./routes/userRoutes');const app = express();
app.use(express.json());
// MongoDB connectionmongoose.connect(process.env.MONGO_URI).then(() => console.log('✅ Connected to MongoDB Atlas')).catch(err => console.error('❌ Connection error:', err));
// API routesapp.use('/api/users', userRoutes);
// Root routeapp.get('/', (req, res) => { res.send('✅ MongoDB Atlas Express API is running!');});
const PORT = process.env.PORT || 3000;app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`));
🧪 Test the API
Use Postman, Insomnia, or curl to test:
➕ Create User (POST)
URL: http://localhost:3000/api/users
Body (JSON):
{ "name": "Alice", "email": "alice@example.com", "age": 28}
📥 Get All Users (GET)
URL: http://localhost:3000/api/users
🔎 Find by Email (GET)
URL: http://localhost:3000/api/users/email/alice@example.com
✅ All Set!
You now have:
- MongoDB Atlas connected
- Users stored in the cloud
- API routes ready for use
- Basic queries and endpoints to build on