Skip to main content

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:
1

Create MongoDB Atlas Account

  1. Go to MongoDB Atlas
  2. Sign up for a free account or log in
  3. Create a new organization (if needed)
2

Create a Cluster

  1. Click “Build a Cluster” or “Create”
  2. Choose the FREE tier (M0) for testing and development
  3. Select a cloud provider and region closest to your application
  4. Name your cluster (e.g., “StockAPI-Cluster”)
  5. Click “Create Cluster” (this may take a few minutes)
3

Configure Database Access

  1. Navigate to Database Access in the left sidebar
  2. Click “Add New Database User”
  3. Choose authentication method: Password
  4. Create a username and secure password
  5. Set user privileges to “Read and write to any database” (or more restricted if preferred)
  6. Click “Add User”
Save your database 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, you can click “Allow Access from Anywhere” (0.0.0.0/0)
  4. For production, add specific IP addresses of your servers
  5. Click “Confirm”
Using 0.0.0.0/0 allows connections from any IP address. This is convenient for development but not recommended for production environments.
5

Get Connection String

  1. Go to Database in the left sidebar
  2. Click “Connect” on your cluster
  3. Choose “Connect your application”
  4. Select Node.js as the driver and the appropriate version
  5. Copy the connection string provided
It will look like:
mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/<database>?retryWrites=true&w=majority

Connection String Format

The MongoDB connection string follows this format:
mongodb+srv://<username>:<password>@<cluster-url>/<database-name>?<options>

Connection String Components

ComponentDescriptionExample
usernameDatabase user created in Atlasstockapi_user
passwordUser password (URL encoded if contains special characters)MyP@ssw0rd
cluster-urlAtlas cluster hostnamecluster0.abc123.mongodb.net
database-nameName of your databasestockapi
optionsConnection options (optional)retryWrites=true&w=majority

Example Connection Strings

MONGO_URI="mongodb+srv://devuser:password123@cluster0.abc123.mongodb.net/stockapi_dev?retryWrites=true&w=majority"
If your password contains special characters (like @, :, /, etc.), you must URL encode them:
  • @ becomes %40
  • : becomes %3A
  • / becomes %2F
Example: MyP@ss:word becomes MyP%40ss%3Aword

How the Application Connects

StockAPI establishes the database connection in the index.js file before starting the Express server.

Connection Code

Here’s how the application connects to MongoDB (from index.js):
index.js
// Modulo que establece la conexion a la data base.
'use strict'

// Variables de entorno
require('dotenv').config(); // Carga las variables del .env

// Modulos
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const port = process.env.PORT || 3000;
const app = require('./app');

// Establecer conexión con MongoDB Atlas
mongoose.connect(process.env.MONGO_URI)
    .then(() => {
        console.log("✅ Conexión a MongoDB Atlas establecida correctamente");

        // En caso de que se haya podido conectar a atlas, levanta el servidor
        app.listen(port, () => {
            console.log(`✅ Servidor funcionando en el puerto ${port}`);
        });
    })
    .catch((error) => console.error("❌ Error al conectar a MongoDB Atlas:", error));

Connection Flow

1

Load Environment Variables

The application loads the .env file using dotenv to access MONGO_URI
2

Attempt Connection

Mongoose attempts to connect to MongoDB Atlas using the connection string from process.env.MONGO_URI
3

Connection Success

If successful, you’ll see:
✅ Conexión a MongoDB Atlas establecida correctamente
✅ Servidor funcionando en el puerto 3000
The Express server only starts after a successful database connection.
4

Connection Failure

If the connection fails, an error is logged:
❌ Error al conectar a MongoDB Atlas: [error details]
The server will not start if it cannot connect to the database.
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
MONGO_URI="mongodb+srv://your-username:your-password@your-cluster.mongodb.net/your-database?retryWrites=true&w=majority"
Replace:
  • your-username with your MongoDB Atlas database username
  • your-password with your database user password
  • your-cluster with your Atlas cluster hostname
  • your-database with your database name (e.g., stockapi)

Troubleshooting Connection Issues

Common Connection Errors

1

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
2

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
3

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
4

Database Not Found

If the database doesn’t exist, MongoDB will create it automatically when you first write data to it. This is normal behavior and not an error.

Testing Your Connection

To test if your connection string works:
node -e "require('mongoose').connect(process.env.MONGO_URI).then(() => console.log('✅ Connected')).catch(err => console.log('❌ Error:', err.message))"

Database Connection Options

Mongoose supports additional connection options that can be appended to your connection string:
MONGO_URI="mongodb+srv://user:pass@cluster.mongodb.net/db?retryWrites=true&w=majority&maxPoolSize=10"

Useful Options

OptionDescriptionDefault
retryWrites=trueAutomatically retry write operationstrue
w=majorityWrite concern level1
maxPoolSizeMaximum connection pool size100
serverSelectionTimeoutMSTimeout for server selection30000
connectTimeoutMSConnection timeout30000

Monitoring Your Connection

You can add event listeners to monitor your database connection:
const mongoose = require('mongoose');

mongoose.connection.on('connected', () => {
  console.log('Mongoose connected to MongoDB Atlas');
});

mongoose.connection.on('error', (err) => {
  console.error('Mongoose connection error:', err);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose disconnected from MongoDB Atlas');
});

Production Best Practices

For production deployments:
  • Use a dedicated production cluster
  • Restrict Network Access to specific IP addresses
  • Use strong, unique passwords
  • Enable MongoDB Atlas backup
  • Monitor database performance and set up alerts
  • Use connection pooling appropriately
  • Implement proper error handling and retry logic

Next Steps