Overview
The Construction Backend API uses MongoDB Atlas as its database solution. This guide walks you through setting up your database connection and configuring it properly for development and production environments.Prerequisites
Before you begin, ensure you have:- A MongoDB Atlas account (create one at mongodb.com/cloud/atlas)
- Node.js installed (v14 or higher)
- Access to your project’s environment variables
Database Connection Architecture
The API uses Mongoose ODM to manage MongoDB connections. The connection is established insrc/database/connection.js:4-23 and includes automatic event handling for connection lifecycle management.
Create MongoDB Atlas Cluster
- Log in to your MongoDB Atlas account
- Click “Build a Database”
- Choose your preferred cluster tier (M0 Free Tier works for development)
- Select your cloud provider and region
- Name your cluster (e.g., “Construction”)
- Click “Create Cluster”
Configure Database Access
- Navigate to “Database Access” in the left sidebar
- Click “Add New Database User”
- Choose authentication method (Password recommended)
- Create username and secure password
- Set user privileges (Read and Write to any database for development)
- 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 specific IP addresses or ranges
- Click “Confirm”
For production deployments on Vercel, use 0.0.0.0/0 as Vercel uses dynamic IPs, or configure Vercel’s IP ranges if available.
Get Connection String
- Navigate to “Database” in the left sidebar
- Click “Connect” on your cluster
- Choose “Connect your application”
- Select “Node.js” driver and version 4.1 or later
- Copy the connection string
- Replace
<password>with your database user password - Replace
<dbname>with your database name (or remove it to use the default)
Environment Configuration
The API usesdotenv to manage environment variables. The database configuration is loaded from src/database/config.js:1-11.
Create Environment File
Create a.env file in your project root:
.env
The
PORT variable defaults to 3000 if not specified. Vercel automatically sets this for production deployments.Required Environment Variables
| Variable | Description | Required | Default |
|---|---|---|---|
MONGO_URI | MongoDB Atlas connection string | Yes | None |
PORT | Server port number | No | 3000 |
Connection Implementation
The database connection is initialized when the application starts. Here’s how it works:src/database/connection.js
src/index.js:11:
src/index.js
Connection Events
The API monitors three key connection events:Connected Event
Fired when successfully connected to MongoDB Atlas. Logs confirmation message.Error Event
Fired when a connection error occurs. Logs error details for debugging.Disconnected Event
Fired when the connection to MongoDB is lost. Logs disconnection notice.Troubleshooting
Connection Timeout
Problem: Application hangs when trying to connect to MongoDB. Solutions:- Verify your IP address is whitelisted in MongoDB Atlas Network Access
- Check that your connection string is correct
- Ensure your MongoDB Atlas cluster is running
- Verify network connectivity
Authentication Failed
Problem: Error message: “Authentication failed” Solutions:- Double-check username and password in connection string
- Ensure the database user has proper permissions
- Verify the password doesn’t contain special characters that need URL encoding
- Try resetting the database user password
MONGO_URI Undefined
Problem: Console showsMONGO_URI: undefined
Solutions:
- Verify
.envfile exists in project root - Check that
dotenv.config()is called before importing config - Ensure
MONGO_URIis properly set in.envfile - Restart your development server after changing
.env
Connection String Format
Problem: Invalid connection string format Solutions:- Use
mongodb+srv://protocol for Atlas connections - Ensure no spaces in the connection string
- URL-encode special characters in username/password
- Include
retryWrites=true&w=majorityparameters
Best Practices
Use Environment Variables
Never hardcode database credentials. Always use environment variables and the
.env file for local development.Connection Pooling
Mongoose automatically manages connection pooling. For high-traffic applications, consider configuring pool size:
Security Considerations
- Never commit credentials: Use
.gitignoreto exclude.envfiles - Use strong passwords: Generate complex passwords for database users
- Limit network access: Only whitelist necessary IP addresses
- Principle of least privilege: Grant minimal required permissions to database users
- Rotate credentials: Regularly update database passwords
- Monitor access: Enable MongoDB Atlas audit logs for production
Verification
To verify your database connection is working:-
Start your development server:
-
Check console output for:
-
Test with the health check endpoint:
If you see “Connected to MongoDB Atlas” in your logs, your database is properly configured!