Skip to main content

MongoDB for JavaScript Developers: Setup, URI, and Atlas

Created: June 12, 2021 4 min read

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

  1. Sign up at cloud.mongodb.com
  2. Create a new project
  3. Build a cluster → choose M0 (free) → select a region
  4. Wait ~3 minutes for provisioning

2. Configure Access

Database User:

  1. Security → Database Access → Add New Database User
  2. Choose “Password” authentication
  3. Set username and a strong password
  4. Role: “Read and write to any database” (for development)

Network Access:

  1. Security → Network Access → Add IP Address
  2. For development: “Allow Access from Anywhere” (0.0.0.0/0)
  3. For production: add only your server’s IP

3. Get the Connection String

  1. Clusters → Connect → Connect your application
  2. Select “Node.js” and your version
  3. Copy the connection string
  4. 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);
// 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

Comments

Share this article

Scan to read on mobile