Source

config/database.js

/**
 * Database Configuration
 * 
 * This module handles MongoDB database connection for the Social Media Dashboard API.
 * It provides a centralized way to connect to MongoDB with proper error handling and logging.
 * 
 * @author Ignas Panavas
 * @version 1.0.0
 */

const mongoose = require('mongoose');
require('dotenv').config();

/**
 * Connect to MongoDB Database
 * 
 * Establishes a connection to the MongoDB database using the URI from environment variables.
 * Falls back to localhost if no MONGODB_URI is provided. Includes proper error handling and logging.
 * 
 * @async
 * @function connectDB
 * @returns {Promise<void>} Resolves when connection is established
 * @throws {Error} If connection fails, the process will exit with code 1
 * 
 * @example
 * // In your main server file
 * const connectDB = require('./config/database');
 * connectDB().then(() => {
 *   console.log('Server ready');
 * });
 */
const connectDB = async () => {
  try {
    const mongoURI = process.env.MONGODB_URI || 'mongodb://localhost:27017/social_media_dashboard';
    
    console.log('🔍 Attempting to connect to MongoDB...');
    console.log('🔍 MONGODB_URI:', mongoURI);
    
    await mongoose.connect(mongoURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    console.log('📊 Connected to MongoDB database');
  } catch (error) {
    console.error('❌ Database connection error:', error);
    process.exit(1);
  }
};

module.exports = connectDB;