Skip to main content
Study Sync uses MongoDB as its primary database for storing study plans, user data, and progress tracking. This guide covers setting up MongoDB Atlas and configuring the connection.

Overview

The application uses the native MongoDB Node.js driver with connection caching to optimize performance in serverless environments. Database name: study_sync Configuration file: src/lib/mongodb.js

Prerequisites

  • MongoDB Atlas account (free tier available)
  • Node.js 14+ installed

Setup Instructions

1

Create MongoDB Atlas Account

Sign up for a free account at MongoDB Atlas.
2

Create a Cluster

  1. Click “Build a Database”
  2. Choose M0 Free tier (or higher for production)
  3. Select your preferred cloud provider and region
  4. Click “Create Cluster” (takes 1-3 minutes)
3

Configure Database Access

  1. Navigate to Database Access in the left sidebar
  2. Click “Add New Database User”
  3. Choose “Password” authentication
  4. Enter username and generate a secure password
  5. Set user privileges to “Read and write to any database”
  6. Click “Add User”
Save the username and password securely. You’ll need them for the connection string.
4

Configure Network Access

  1. Navigate to Network Access in the left sidebar
  2. Click “Add IP Address”
  3. For development: Click “Allow Access from Anywhere” (0.0.0.0/0)
  4. For production: Add your server’s specific IP address
  5. Click “Confirm”
Allowing access from anywhere (0.0.0.0/0) is convenient for development but less secure. For production, restrict to specific IP addresses.
5

Get Connection String

  1. Navigate to Database and click “Connect” on your cluster
  2. Choose “Connect your application”
  3. Select “Node.js” as driver and version “4.1 or later”
  4. Copy the connection string:
mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/?retryWrites=true&w=majority
6

Configure Environment Variable

  1. Replace <username> and <password> with your database user credentials
  2. Add database name after the / before the ?:
MONGODB_URI=mongodb+srv://username:[email protected]/study_sync?retryWrites=true&w=majority
  1. Add this to your .env.local file

Connection Configuration

The MongoDB connection is configured in src/lib/mongodb.js:
import { MongoClient } from "mongodb";

/**
 * MongoDB connection for Next.js API Routes
 * Uses native MongoDB driver with connection caching
 */

if (!process.env.MONGODB_URI) {
  throw new Error("Please add your MONGODB_URI to .env.local");
}

const MONGODB_URI = process.env.MONGODB_URI;
const options = {};

let client;
let clientPromise;

if (process.env.NODE_ENV === "development") {
  // In development, use a global variable to preserve the connection across hot reloads
  if (!global._mongoClientPromise) {
    client = new MongoClient(MONGODB_URI, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  // In production, create a new client
  client = new MongoClient(MONGODB_URI, options);
  clientPromise = client.connect();
}

/**
 * Get database instance
 */
export async function getDb() {
  try {
    const client = await clientPromise;
    return client.db("study_sync");
  } catch (error) {
    console.error("MongoDB connection error:", error);
    throw error;
  }
}

export default clientPromise;

Connection Caching

The configuration implements connection caching to optimize performance:

Development Mode

  • Uses global._mongoClientPromise to persist connection across hot reloads
  • Prevents connection pool exhaustion during development
  • Reuses the same connection for multiple requests

Production Mode

  • Creates fresh client connections
  • Better suited for serverless environments
  • Automatically managed by MongoDB driver

Database Structure

Study Sync uses the following collections:

Collections

  • users - User profiles and preferences
  • studyPlans - Master study plan templates
  • instances - User-specific study plan instances
  • progress - Progress tracking for materials
  • reminders - Custom reminder settings

Indexes

The application automatically creates indexes for optimal query performance. Common indexed fields include:
  • users.firebaseUid - For user lookups
  • studyPlans.ownerId - For filtering plans by owner
  • instances.userId - For user instance queries
  • instances.deadline - For deadline-based queries

Usage Examples

Get Database Instance

import { getDb } from '@/lib/mongodb';

export default async function handler(req, res) {
  try {
    const db = await getDb();
    
    // Now you can use db to query collections
    const users = db.collection('users');
    const user = await users.findOne({ firebaseUid: 'abc123' });
    
    res.json({ user });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

Insert Document

const db = await getDb();
const studyPlans = db.collection('studyPlans');

const result = await studyPlans.insertOne({
  title: "JavaScript Fundamentals",
  ownerId: "user123",
  materials: [],
  createdAt: new Date()
});

console.log('Inserted ID:', result.insertedId);

Query Documents

const db = await getDb();
const instances = db.collection('instances');

// Find all active instances for a user
const userInstances = await instances
  .find({ 
    userId: 'user123',
    status: 'active'
  })
  .sort({ deadline: 1 })
  .toArray();

Update Document

const db = await getDb();
const progress = db.collection('progress');

const result = await progress.updateOne(
  { _id: ObjectId('...') },
  { 
    $set: { completed: true, completedAt: new Date() }
  }
);

Troubleshooting

”Please add your MONGODB_URI to .env.local”

Cause: The MONGODB_URI environment variable is not set. Solution: Add the connection string to your .env.local file and restart your development server.

Connection Timeout Errors

Possible causes:
  1. Network access not configured correctly
  2. Incorrect IP address whitelist
  3. Invalid connection string
Solutions:
  1. Verify your IP is whitelisted in MongoDB Atlas Network Access
  2. Try allowing access from anywhere (0.0.0.0/0) temporarily for testing
  3. Check connection string format and credentials

Authentication Failed

Cause: Incorrect username or password in connection string. Solutions:
  1. Verify credentials in MongoDB Atlas Database Access
  2. Ensure special characters in password are URL-encoded
  3. Reset database user password if needed

URL Encoding Special Characters

If your password contains special characters, they must be URL-encoded:
CharacterEncoded
@%40
:%3A
/%2F
?%3F
#%23
[%5B
]%5D
Example:
# Password: p@ss:word
# Encoded: p%40ss%3Aword
MONGDB_URI=mongodb+srv://user:p%40ss%[email protected]/study_sync

Connection Pool Exhaustion

Cause: Too many connections in development due to hot reloading. Solution: The configuration already handles this with global._mongoClientPromise. If issues persist, restart your development server.

Production Considerations

Cluster Configuration

For production deployments:
  1. Use dedicated cluster: Upgrade from M0 free tier to M10+ for better performance
  2. Enable backups: Configure automated backups in Atlas
  3. Set up monitoring: Enable Atlas monitoring and alerts
  4. Use replicas: Ensure your cluster has replica sets for high availability

Connection String Options

Recommended production connection string options:
MONGDB_URI=mongodb+srv://user:[email protected]/study_sync?retryWrites=true&w=majority&maxPoolSize=10&minPoolSize=2
Options explained:
  • retryWrites=true - Automatically retry write operations
  • w=majority - Wait for majority of nodes to confirm writes
  • maxPoolSize=10 - Maximum number of connections in pool
  • minPoolSize=2 - Minimum number of connections to maintain

IP Whitelisting

For production, restrict access to specific IPs:
  1. Get your server/hosting platform’s outbound IP addresses
  2. Add each IP to MongoDB Atlas Network Access
  3. Remove the 0.0.0.0/0 wildcard entry

Environment Variables

Set MONGODB_URI in your hosting platform:
  • Vercel: Project Settings > Environment Variables > Production
  • Netlify: Site Settings > Environment Variables
  • Other platforms: Refer to platform documentation
Use different MongoDB clusters for development and production to prevent accidental data corruption.

Security Best Practices

  1. Use strong passwords: Generate complex passwords for database users
  2. Restrict network access: Whitelist only necessary IP addresses
  3. Limit user privileges: Grant minimum required permissions
  4. Enable audit logs: Track database access in production
  5. Rotate credentials: Change passwords periodically
  6. Use VPC peering: For enhanced security in production (Atlas M10+)
  7. Enable encryption: Use encrypted connections (default with mongodb+srv://)

Monitoring and Maintenance

Atlas Monitoring

MongoDB Atlas provides built-in monitoring:
  1. Navigate to your cluster in Atlas
  2. Click “Metrics” tab
  3. Monitor:
    • Connection count
    • Query performance
    • Storage usage
    • Network traffic

Performance Optimization

  1. Create indexes: For frequently queried fields
  2. Use projections: Only fetch needed fields
  3. Limit results: Use .limit() for pagination
  4. Monitor slow queries: Enable query profiling in Atlas

Database Backups

  1. Navigate to Backup in Atlas
  2. Enable Continuous Backup (M10+ clusters)
  3. Configure backup schedule and retention policy
  4. Test restoration process periodically

Resources

Build docs developers (and LLMs) love