MONGODB SETUP COMPLETE GUIDE

Comprehensive guidelines for AI-assisted development within the Editor platform

๐Ÿƒ Complete MongoDB Setup Guide for Singularity

Your comprehensive guide to setting up MongoDB Atlas for the Singularity app


๐ŸŽฏ What We're Setting Up

MongoDB Atlas will serve as your primary production database for:

๐Ÿ—๏ธ Current Architecture


๐Ÿ”ง Step 1: VS Code MongoDB Extension Setup

Install MongoDB for VS Code

  1. Open VS Code
  2. Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X)
  3. Search for: MongoDB for VS Code
  4. Install the official extension by MongoDB

Connect to Your Database

  1. Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
  2. Type: MongoDB: Connect
  3. Select: Connect with Connection String
  4. Paste your connection string (get from .env.local):
    # Format: mongodb+srv://<USERNAME>:<URL_ENCODED_PASSWORD>@<CLUSTER>.mongodb.net/
    # ๐Ÿ”’ Get actual value from your .env.local file
    

โœ… You should now see your MongoDB databases in the VS Code sidebar!


๐Ÿ›ก๏ธ Step 2: Understanding CORS Issues (Current Problem)

Why You're Getting CORS Errors

The error you're seeing:

Access to XMLHttpRequest at 'https://data.mongodb-api.com/app/data-hnbqp/endpoint/data/v1/action/findOne' 
from origin 'http://localhost:5400' has been blocked by CORS policy

Explanation:

This is EXPECTED and NORMAL โœ…


๐ŸŽฏ Step 3: Current Status (What's Working)

Based on your logs, here's what's already working perfectly:

โœ… Local Development (Perfect!)

โœ… Local database test successful (23.50ms)
โœ… Comprehensive local database connected successfully  
๐Ÿ“Š Local database stats: {logic-blocks: 1, performance-metrics: 40829, ...}

โœ… Firebase (Perfect!)

โœ… User authenticated: q8xJ4lnHyoV6zXR8urxMp2sRSy82
โœ… Firebase Firestore connected successfully

โŒ MongoDB (Expected CORS Issues)

โŒ CORS policy blocked MongoDB Atlas Data API

โธ๏ธ Redis (Disabled - Expected)

โธ๏ธ Redis is disabled for local development

๐Ÿš€ Step 4: Recommended Production Setup

Option A: Server-Side Integration (Recommended)

Create a Node.js backend that connects to MongoDB:

// backend/mongodb-proxy.js
import { MongoClient } from 'mongodb';
import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());
app.use(express.json());

// ๐Ÿ”’ Get connection string from environment variable (loaded from .env.local)
const mongoUri = process.env.MONGODB_CONNECTION_STRING;
const client = new MongoClient(mongoUri);

// Proxy endpoint for logic blocks
app.post('/api/logic-blocks', async (req, res) => {
  try {
    await client.connect();
    const db = client.db('singularity');
    const collection = db.collection('logic-blocks');
    
    const result = await collection.insertOne(req.body);
    res.json({ id: result.insertedId });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3001, () => {
  console.log('๐Ÿƒ MongoDB proxy server running on port 3001');
});

Option B: MongoDB Atlas App Services (Advanced)

  1. Go to MongoDB Atlas Dashboard
  2. Navigate to App Services
  3. Create a new App
  4. Enable Data API
  5. Configure CORS settings
  6. Create API endpoints

๐Ÿ”ง Step 5: Current App Integration

Your Connection String Location

Your MongoDB connection is configured in:

// apps/singularity/src/app/core/services/mongodb-integration.service.ts
const MONGODB_CONFIG = {
  // ๐Ÿ”’ Get from environment - NEVER hardcode credentials
  connectionString: getEnvironmentVariable('NX_MONGODB_CONNECTION_STRING'),
  database: 'singularity-dev',
  apiKey: getEnvironmentVariable('NX_MONGODB_API_KEY')
};

Environment Variables Setup

Add to your .env file:

# MongoDB Atlas Data API Key (if using direct API)
NX_MONGODB_API_KEY=your-api-key-here

# MongoDB Connection String (๐Ÿ”’ get from MongoDB Atlas Dashboard)
NX_MONGODB_CONNECTION_STRING=mongodb+srv://<USERNAME>:<URL_ENCODED_PASSWORD>@<CLUSTER>.mongodb.net/

๐Ÿงช Step 6: Testing Your Setup

Test in VS Code

  1. Open MongoDB extension panel
  2. Expand your connection
  3. Browse your databases
  4. Create a test collection

Test Connection String

// You can test this in VS Code terminal
const { MongoClient } = require('mongodb');

// ๐Ÿ”’ Use env-loader to read from .env.local (the correct way!)
import { getMongoDBConnectionString } from './env-loader.js';
const uri = getMongoDBConnectionString();
const client = new MongoClient(uri);

async function testConnection() {
  try {
    await client.connect();
    console.log('โœ… Connected to MongoDB!');
    
    // List databases
    const dbs = await client.db().admin().listDatabases();
    console.log('๐Ÿ“Š Available databases:', dbs.databases.map(db => db.name));
    
    await client.close();
  } catch (error) {
    console.error('โŒ Connection failed:', error);
  }
}

testConnection();

๐ŸŽฏ Step 7: Immediate Next Steps

For Development (Right Now)

  1. โœ… Keep using IndexedDB - it's working perfectly!
  2. โœ… Firebase sync works - you'll see data there
  3. โš ๏ธ Ignore MongoDB CORS errors - they're expected in browser
  4. ๐ŸŽฏ Focus on building features - database is ready!

For Production (Later)

  1. ๐Ÿ”ง Set up Node.js backend for MongoDB proxy
  2. ๐Ÿ”‘ Configure MongoDB Atlas App Services
  3. ๐Ÿ›ก๏ธ Implement proper authentication
  4. ๐Ÿš€ Deploy with proper server-side access

๐Ÿ“Š Database Usage Patterns

Current Data Flow

graph TD
    A[User Creates Block] --> B[Save to IndexedDB]
    B --> C[Update NGXS State]
    C --> D[Sync to Firebase]
    D --> E[Real-time Updates]
    
    style A fill:#e1f5fe
    style B fill:#e8f5e8
    style D fill:#fff3e0
    style E fill:#f3e5f5

Production Data Flow (Future)

graph TD
    A[User Creates Block] --> B[Save to IndexedDB]
    B --> C[Update NGXS State] 
    C --> D[Send to Backend API]
    D --> E[Save to MongoDB]
    E --> F[Sync to Firebase]
    F --> G[Real-time Updates]
    
    style A fill:#e1f5fe
    style B fill:#e8f5e8
    style D fill:#fff3e0
    style E fill:#e8f5e8
    style F fill:#fff3e0
    style G fill:#f3e5f5

๐Ÿšจ Common Issues & Solutions

Issue 1: CORS Errors

โŒ CORS policy blocked MongoDB Atlas Data API

Solution: This is expected in browser. Use server-side proxy or Firebase for now.

Issue 2: Authentication Errors

โŒ Authentication failed

Solution: Check your username/password in connection string. Try mongosh to test.

Issue 3: Network Errors

โŒ Network timeout

Solution: Check your IP whitelist in MongoDB Atlas Network Access.

Issue 4: Database Not Found

โŒ Database 'singularity' not found

Solution: Databases are created automatically when you insert first document.


๐ŸŽ‰ Success Indicators

โœ… VS Code Connection Working

โœ… App Integration Working

๐ŸŽฏ You're Ready to Continue Building!

Your current setup is PERFECT for development!

The CORS errors are expected and don't prevent you from building features. Focus on:

  1. โœจ Building amazing logic blocks
  2. ๐ŸŽจ Improving the UI/UX
  3. ๐Ÿš€ Adding new features

MongoDB will be there when you're ready for production! ๐Ÿƒ


๐Ÿ”ฎ Advanced Configuration (Optional)

Custom Database Names

// Custom database per environment
const getDatabase = () => {
  const env = process.env['NODE_ENV'] || 'development';
  return `singularity-${env}`;
};

Performance Optimization

// Connection pooling
const clientOptions = {
  maxPoolSize: 10,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
};

Security Best Practices


๐Ÿ“š Useful Resources

You're all set to continue building your amazing Singularity app! ๐Ÿš€๐ŸŒŒ