058
LVL 03 — MID DEVELOPER SESSION 058 DAY 58

MONGO DB

🎫 PIXELCRAFT-045
🐛 Bug | 🟠 Hard | Priority: 🔴 Critical

Restarting the server wipes all data (it was stored in a JS array). We need a real database. Data must survive restarts, handle concurrent users, and scale.
CONCEPTS.UNLOCKED
💾
Why Databases Exist
Persistence, concurrency, querying, integrity. Data survives crashes. Multiple users read/write simultaneously. Find specific records instantly. Data stays consistent.
SQL vs NoSQL
Relational (SQL): tables, rows, strict schema, SQL language. Document (NoSQL): collections, JSON-like documents, flexible structure. Different tools for different problems.
🍃
MongoDB
Document database — stores JSON-like documents (BSON). No table schemas to define upfront. Flexible structure that maps naturally to JavaScript objects.
📂
Core Concepts
Database (pixelcraft) → Collections (images, users) → Documents ({ name: "photo.jpg", width: 1920 }). Like: filesystem → folders → files.
CRUD in MongoDB
insertOne (create), find (read many), findOne (read one), updateOne (update), deleteOne (delete). The same four operations as the REST API — now at the database level.
🔭
MongoDB Compass
Visual database explorer. See collections, browse documents, run queries, create indexes — all in a GUI. Like DevTools for your database.
HANDS-ON.TASKS
01
Set Up MongoDB

Set up MongoDB (local install or Atlas free tier). Atlas gives you a cloud database in minutes — no installation needed.

02
Connect from Node.js
const { MongoClient } = require('mongodb'); const client = new MongoClient( 'mongodb://localhost:27017' ); async function connectDB() { await client.connect(); console.log('Connected to MongoDB'); return client.db('pixelcraft'); }
03
Replace In-Memory Array with MongoDB
// GET all images app.get('/api/images', async (req, res) => { const db = await connectDB(); const images = await db.collection('images') .find().toArray(); res.json(images); }); // POST new image app.post('/api/images', async (req, res) => { const db = await connectDB(); const image = { ...req.body, createdAt: new Date(), }; const result = await db.collection('images') .insertOne(image); res.status(201).json({ ...image, _id: result.insertedId }); });
The API looks almost the same. The big difference: data now lives in MongoDB instead of a JavaScript variable. Restart the server → data is still there.
04
Test Persistence

Add images via API → restart server → images are still there! This is the whole point. Data persists independently of the application.

05
Explore with MongoDB Compass

Open MongoDB Compass. Connect to your database. See the pixelcraft database, the images collection, the documents you created. Run queries visually.

06
Close the Ticket
git switch -c feature/PIXELCRAFT-045-mongodb git add server/ package.json git commit -m "Integrate MongoDB for persistent storage (PIXELCRAFT-045)" git push origin feature/PIXELCRAFT-045-mongodb # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Database fundamentals.

CRUD + guarantees. ACID has defined database engineering for decades.

// ACID guarantees:

Atomicity   → operations complete fully
               or not at all
Consistency → data always valid
Isolation   → concurrent operations
               don't interfere
Durability  → committed data
               survives crashes

// MongoDB relaxes some ACID for
// flexibility and speed.
// SQL (PostgreSQL, MySQL) enforces
// strict ACID.
// The choice depends on your needs.
"Database Lab"
[A] Implement all CRUD operations with MongoDB: updateOne (change image name), deleteOne (remove image), find with a filter (images by format). Test each with curl.
[B] Add a "settings" collection: save user preferences (theme, default export format) to the database. Load on app start. Preferences persist across sessions and devices.
[C] Research: when would you choose PostgreSQL over MongoDB? List 3 scenarios where SQL is better (financial records, complex relations, strict validation) and 3 where MongoDB wins.
REF.MATERIAL
ARTICLE
MongoDB
Official intro: document model, BSON, collections, CRUD operations, and why document databases suit modern applications.
MONGODBOFFICIALESSENTIAL
VIDEO
Fireship
Ultra-fast MongoDB overview: document model, collections, queries, indexing, and when to choose it over SQL.
MONGODBQUICK
ARTICLE
MongoDB
Official Node.js driver docs: connection, CRUD operations, aggregation, indexes, and transactions. The API you just used.
NODE.JSDRIVEROFFICIAL
ARTICLE
Wikipedia
The guarantees that define database reliability: Atomicity, Consistency, Isolation, Durability. The theory behind every production database.
ACIDTHEORYCS
VIDEO
Fireship
Side-by-side comparison: relational vs document databases, when each shines, and the tradeoffs you need to understand.
SQLNOSQLCOMPARISON
// LEAVE EXCITED BECAUSE
Data is real now. It survives server restarts. You can query it, search it, update it. PixelCraft has permanent memory.