Overview
StockAPI uses MongoDB Atlas as its database solution. This guide explains how to set up your MongoDB Atlas cluster, configure the connection string, and understand how the application connects to the database.MongoDB Atlas Setup
MongoDB Atlas is a fully-managed cloud database service. Follow these steps to set up your database:Create MongoDB Atlas Account
- Go to MongoDB Atlas
- Sign up for a free account or log in
- Create a new organization (if needed)
Create a Cluster
- Click “Build a Cluster” or “Create”
- Choose the FREE tier (M0) for testing and development
- Select a cloud provider and region closest to your application
- Name your cluster (e.g., “StockAPI-Cluster”)
- Click “Create Cluster” (this may take a few minutes)
Configure Database Access
- Navigate to Database Access in the left sidebar
- Click “Add New Database User”
- Choose authentication method: Password
- Create a username and secure password
- Set user privileges to “Read and write to any database” (or more restricted if preferred)
- Click “Add User”
Save your database username and password securely - you’ll need them for the connection string.
Configure Network Access
- Navigate to Network Access in the left sidebar
- Click “Add IP Address”
- For development, you can click “Allow Access from Anywhere” (0.0.0.0/0)
- For production, add specific IP addresses of your servers
- Click “Confirm”
Connection String Format
The MongoDB connection string follows this format:Connection String Components
| Component | Description | Example |
|---|---|---|
username | Database user created in Atlas | stockapi_user |
password | User password (URL encoded if contains special characters) | MyP@ssw0rd |
cluster-url | Atlas cluster hostname | cluster0.abc123.mongodb.net |
database-name | Name of your database | stockapi |
options | Connection options (optional) | retryWrites=true&w=majority |
Example Connection Strings
How the Application Connects
StockAPI establishes the database connection in theindex.js file before starting the Express server.
Connection Code
Here’s how the application connects to MongoDB (fromindex.js):
index.js
Connection Flow
Attempt Connection
Mongoose attempts to connect to MongoDB Atlas using the connection string from
process.env.MONGO_URIConnection Success
If successful, you’ll see:The Express server only starts after a successful database connection.
StockAPI uses a “connect-first” strategy, meaning the server won’t start until the database connection is established. This prevents the API from accepting requests when the database is unavailable.
Configure Your Connection
Add your MongoDB connection string to the.env file:
.env
your-usernamewith your MongoDB Atlas database usernameyour-passwordwith your database user passwordyour-clusterwith your Atlas cluster hostnameyour-databasewith your database name (e.g.,stockapi)
Troubleshooting Connection Issues
Common Connection Errors
Authentication Failed
Error:
MongoServerError: bad auth: Authentication failedSolutions:- Verify username and password are correct
- Check if password is URL encoded (especially if it contains special characters)
- Ensure the database user exists in Atlas Database Access settings
Network Timeout
Error:
MongooseServerSelectionError: connect ETIMEDOUTSolutions:- Check your Network Access IP whitelist in MongoDB Atlas
- Add your current IP address or use 0.0.0.0/0 for testing
- Verify your internet connection
- Check if you’re behind a firewall blocking port 27017
Invalid Connection String
Error:
MongoParseError: Invalid connection stringSolutions:- Verify the connection string format is correct
- Ensure there are no extra spaces or line breaks
- Check that special characters in password are URL encoded
- Make sure you replaced
<username>,<password>, and<database>placeholders
Testing Your Connection
To test if your connection string works:Database Connection Options
Mongoose supports additional connection options that can be appended to your connection string:Useful Options
| Option | Description | Default |
|---|---|---|
retryWrites=true | Automatically retry write operations | true |
w=majority | Write concern level | 1 |
maxPoolSize | Maximum connection pool size | 100 |
serverSelectionTimeoutMS | Timeout for server selection | 30000 |
connectTimeoutMS | Connection timeout | 30000 |
Monitoring Your Connection
You can add event listeners to monitor your database connection:Production Best Practices
Next Steps
- Environment Setup - Configure all environment variables
- Docker Deployment - Deploy with Docker
- Check MongoDB Atlas documentation for advanced configuration