Introduction
This guide covers the essentials for JavaScript developers working with MongoDB โ from understanding the connection URI to setting up a real application with Node.js, Express, and MongoDB Atlas. Based on the M220JS course from MongoDB University.
What You’ll Build: mflix
The example application is mflix โ a movie browsing application that demonstrates real-world MongoDB patterns:
- Create and share database connections efficiently
- Write data with different levels of durability
- Handle errors from the driver gracefully
- Implement pagination, filtering, and aggregation
Stack: Node.js + Express + MongoDB + React
The MongoDB URI
The MongoDB connection string (URI) tells the driver how to connect to your database:
mongodb+srv://<username>:<password>@<host>/<database>?retryWrites=true
URI Components
mongodb+srv://alice:[email protected]/mflix?retryWrites=true&w=majority
โ โ โ โ โ โ
โ โ โ โ โ โโโ Options
โ โ โ โ โโโ Database name
โ โ โ โโโ Host (Atlas cluster hostname)
โ โ โโโ Password
โ โโโ Username
โโโ Protocol (srv = DNS seedlist, resolves to multiple hosts)
URI Formats
# Atlas (SRV format โ recommended)
mongodb+srv://username:[email protected]/mydb
# Standard format (explicit hosts)
mongodb://username:password@host1:27017,host2:27017/mydb?replicaSet=rs0
# Local development
mongodb://localhost:27017/mydb
# With authentication database
mongodb://username:password@localhost:27017/mydb?authSource=admin
Connection Options
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, {
// Connection pool size
maxPoolSize: 50,
minPoolSize: 5,
// Timeouts
serverSelectionTimeoutMS: 5000, // how long to wait for server selection
socketTimeoutMS: 45000, // how long to wait for socket operations
connectTimeoutMS: 10000, // how long to wait for initial connection
// Write concern
w: 'majority',
wtimeoutMS: 2500,
// Read preference
readPreference: 'primaryPreferred',
// Retry
retryWrites: true,
retryReads: true,
});
Setting Up MongoDB Atlas
Atlas is MongoDB’s cloud database service. The free tier (M0) is sufficient for development.
1. Create a Cluster
- Sign up at cloud.mongodb.com
- Create a new project
- Build a cluster โ choose M0 (free) โ select a region
- Wait ~3 minutes for provisioning
2. Configure Access
Database User:
- Security โ Database Access โ Add New Database User
- Choose “Password” authentication
- Set username and a strong password
- Role: “Read and write to any database” (for development)
Network Access:
- Security โ Network Access โ Add IP Address
- For development: “Allow Access from Anywhere” (0.0.0.0/0)
- For production: add only your server’s IP
3. Get the Connection String
- Clusters โ Connect โ Connect your application
- Select “Node.js” and your version
- Copy the connection string
- Replace
<password>with your actual password
# Store in .env file (never commit this!)
MONGODB_URI=mongodb+srv://alice:[email protected]/mflix?retryWrites=true&w=majority
Connecting with Node.js
Basic Connection
const { MongoClient } = require('mongodb');
require('dotenv').config();
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db('mflix');
const movies = db.collection('movies');
// Find a movie
const movie = await movies.findOne({ title: 'The Matrix' });
console.log(movie?.title);
} finally {
await client.close();
}
}
main().catch(console.error);
Connection Singleton (Recommended for Express)
// db/connection.js
const { MongoClient } = require('mongodb');
let client;
let db;
async function connectToDatabase() {
if (db) return db; // return cached connection
client = new MongoClient(process.env.MONGODB_URI, {
maxPoolSize: 50,
serverSelectionTimeoutMS: 5000,
});
await client.connect();
db = client.db(process.env.DB_NAME || 'mflix');
console.log('Connected to MongoDB');
return db;
}
async function closeConnection() {
if (client) {
await client.close();
client = null;
db = null;
}
}
module.exports = { connectToDatabase, closeConnection };
// app.js
const express = require('express');
const { connectToDatabase } = require('./db/connection');
const app = express();
app.use(express.json());
// Connect once at startup
connectToDatabase().then(() => {
app.listen(3000, () => console.log('Server running on port 3000'));
}).catch(err => {
console.error('Failed to connect to MongoDB:', err);
process.exit(1);
});
// Use in routes
app.get('/movies', async (req, res) => {
const db = await connectToDatabase();
const movies = await db.collection('movies')
.find({})
.limit(20)
.toArray();
res.json(movies);
});
Basic CRUD Operations
const db = await connectToDatabase();
const movies = db.collection('movies');
// Create
await movies.insertOne({
title: 'The Matrix',
year: 1999,
genres: ['Action', 'Sci-Fi'],
imdb: { rating: 8.7, votes: 1800000 }
});
// Read
const matrix = await movies.findOne({ title: 'The Matrix' });
const sciFiMovies = await movies.find({ genres: 'Sci-Fi' }).toArray();
// Update
await movies.updateOne(
{ title: 'The Matrix' },
{ $set: { 'imdb.rating': 8.8 } }
);
// Delete
await movies.deleteOne({ title: 'The Matrix' });
Environment Setup
# Install dependencies
npm install mongodb dotenv express
# .env file
MONGODB_URI=mongodb+srv://...
DB_NAME=mflix
PORT=3000
# .gitignore โ never commit credentials
.env
node_modules/
Resources
- MongoDB Node.js Driver Documentation
- MongoDB Atlas
- MongoDB University M220JS Course
- MongoDB CRUD Operations
Comments