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
Create MongoDB Atlas Account
Sign up for a free account at MongoDB Atlas.
Create a Cluster
- Click “Build a Database”
- Choose M0 Free tier (or higher for production)
- Select your preferred cloud provider and region
- Click “Create Cluster” (takes 1-3 minutes)
Configure Database Access
- Navigate to Database Access in the left sidebar
- Click “Add New Database User”
- Choose “Password” authentication
- Enter username and generate a secure password
- Set user privileges to “Read and write to any database”
- Click “Add User”
Configure Network Access
- Navigate to Network Access in the left sidebar
- Click “Add IP Address”
- For development: Click “Allow Access from Anywhere” (0.0.0.0/0)
- For production: Add your server’s specific IP address
- Click “Confirm”
Get Connection String
- Navigate to Database and click “Connect” on your cluster
- Choose “Connect your application”
- Select “Node.js” as driver and version “4.1 or later”
- Copy the connection string:
Connection Configuration
The MongoDB connection is configured insrc/lib/mongodb.js:
Connection Caching
The configuration implements connection caching to optimize performance:Development Mode
- Uses
global._mongoClientPromiseto 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 lookupsstudyPlans.ownerId- For filtering plans by ownerinstances.userId- For user instance queriesinstances.deadline- For deadline-based queries
Usage Examples
Get Database Instance
Insert Document
Query Documents
Update Document
Troubleshooting
”Please add your MONGODB_URI to .env.local”
Cause: TheMONGODB_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:- Network access not configured correctly
- Incorrect IP address whitelist
- Invalid connection string
- Verify your IP is whitelisted in MongoDB Atlas Network Access
- Try allowing access from anywhere (0.0.0.0/0) temporarily for testing
- Check connection string format and credentials
Authentication Failed
Cause: Incorrect username or password in connection string. Solutions:- Verify credentials in MongoDB Atlas Database Access
- Ensure special characters in password are URL-encoded
- Reset database user password if needed
URL Encoding Special Characters
If your password contains special characters, they must be URL-encoded:| Character | Encoded |
|---|---|
| @ | %40 |
| : | %3A |
| / | %2F |
| ? | %3F |
| # | %23 |
| [ | %5B |
| ] | %5D |
Connection Pool Exhaustion
Cause: Too many connections in development due to hot reloading. Solution: The configuration already handles this withglobal._mongoClientPromise. If issues persist, restart your development server.
Production Considerations
Cluster Configuration
For production deployments:- Use dedicated cluster: Upgrade from M0 free tier to M10+ for better performance
- Enable backups: Configure automated backups in Atlas
- Set up monitoring: Enable Atlas monitoring and alerts
- Use replicas: Ensure your cluster has replica sets for high availability
Connection String Options
Recommended production connection string options:retryWrites=true- Automatically retry write operationsw=majority- Wait for majority of nodes to confirm writesmaxPoolSize=10- Maximum number of connections in poolminPoolSize=2- Minimum number of connections to maintain
IP Whitelisting
For production, restrict access to specific IPs:- Get your server/hosting platform’s outbound IP addresses
- Add each IP to MongoDB Atlas Network Access
- Remove the 0.0.0.0/0 wildcard entry
Environment Variables
SetMONGODB_URI in your hosting platform:
- Vercel: Project Settings > Environment Variables > Production
- Netlify: Site Settings > Environment Variables
- Other platforms: Refer to platform documentation
Security Best Practices
- Use strong passwords: Generate complex passwords for database users
- Restrict network access: Whitelist only necessary IP addresses
- Limit user privileges: Grant minimum required permissions
- Enable audit logs: Track database access in production
- Rotate credentials: Change passwords periodically
- Use VPC peering: For enhanced security in production (Atlas M10+)
- Enable encryption: Use encrypted connections (default with mongodb+srv://)
Monitoring and Maintenance
Atlas Monitoring
MongoDB Atlas provides built-in monitoring:- Navigate to your cluster in Atlas
- Click “Metrics” tab
- Monitor:
- Connection count
- Query performance
- Storage usage
- Network traffic
Performance Optimization
- Create indexes: For frequently queried fields
- Use projections: Only fetch needed fields
- Limit results: Use
.limit()for pagination - Monitor slow queries: Enable query profiling in Atlas
Database Backups
- Navigate to Backup in Atlas
- Enable Continuous Backup (M10+ clusters)
- Configure backup schedule and retention policy
- Test restoration process periodically