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:
- โ Logic Blocks: Store user-created logic blocks
- โ Logic Connections: Store relationships between blocks
- โ Logic Trees: Store complete logic workflows
- โ User Data: Store user-specific configurations
- โ Real-time Sync: Enable collaborative features
๐๏ธ Current Architecture
- Local Development: IndexedDB (browser database) โ Working
- Firebase: Real-time sync โ Working
- MongoDB Atlas: Production data store โ ๏ธ Needs Setup
- Redis: Performance cache (disabled for now) โธ๏ธ
๐ง Step 1: VS Code MongoDB Extension Setup
Install MongoDB for VS Code
- Open VS Code
- Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X)
- Search for:
MongoDB for VS Code - Install the official extension by MongoDB
Connect to Your Database
- Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
- Type:
MongoDB: Connect - Select:
Connect with Connection String - 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:
- โ MongoDB Atlas Data API doesn't allow direct browser access by default
- ๐ CORS policy blocks cross-origin requests for security
- ๐ Browser limitation: Can't directly call MongoDB from frontend
This is EXPECTED and NORMAL โ
- Your local development should use IndexedDB (which works perfectly!)
- MongoDB is for production server-side access
- Firebase handles real-time sync (which works!)
๐ฏ 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)
- Go to MongoDB Atlas Dashboard
- Navigate to App Services
- Create a new App
- Enable Data API
- Configure CORS settings
- 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
- Open MongoDB extension panel
- Expand your connection
- Browse your databases
- 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)
- โ Keep using IndexedDB - it's working perfectly!
- โ Firebase sync works - you'll see data there
- โ ๏ธ Ignore MongoDB CORS errors - they're expected in browser
- ๐ฏ Focus on building features - database is ready!
For Production (Later)
- ๐ง Set up Node.js backend for MongoDB proxy
- ๐ Configure MongoDB Atlas App Services
- ๐ก๏ธ Implement proper authentication
- ๐ 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
- You can see databases in MongoDB extension
- You can browse collections
- You can run queries
โ App Integration Working
- IndexedDB saves blocks โ (You have this!)
- Firebase syncs data โ (You have this!)
- MongoDB ready for production setup
๐ฏ 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:
- โจ Building amazing logic blocks
- ๐จ Improving the UI/UX
- ๐ 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
- ๐ Use strong passwords
- ๐ก๏ธ Enable IP whitelisting
- ๐ Use MongoDB Atlas App Services for browser access
- ๐ Implement proper CORS policies
๐ Useful Resources
- MongoDB Atlas: https://cloud.mongodb.com/
- MongoDB Drivers: https://docs.mongodb.com/drivers/
- VS Code Extension: https://marketplace.visualstudio.com/items?itemName=mongodb.mongodb-vscode
- CORS Understanding: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
You're all set to continue building your amazing Singularity app! ๐๐