📖 Notes LESSON 26 OF 32

MongoDB & Mongoose

⏱️ 32 min
🟢 Node.js

From Arrays to a Real Database

Lesson 25's in-memory array resets every time the server restarts. MongoDB stores data permanently as JSON-like documents; Mongoose gives you schemas and a clean API to work with it.

Schemas, Models, CRUD

🍃
MongoDB
A NoSQL database that stores flexible, JSON-like documents instead of rigid table rows.
📐
Schema
Mongoose's definition of a document's shape — field names, types, required rules.
🏗️
Model
A schema compiled into a class with methods like .find(), .create().
🔗
Connection String
The URI Mongoose uses to connect to a local database or a hosted one like Atlas.
Schema, Model & CRUD
JS
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/coursesdb');

const courseSchema = new mongoose.Schema({
  title: { type: String, required: true },
  category: String,
  hours: Number
});

const Course = mongoose.model('Course', courseSchema);

// Create
await Course.create({ title: 'CSS Grid', category: 'Frontend', hours: 3 });

// Read
const all = await Course.find();
const one = await Course.findById(id);

// Update
await Course.findByIdAndUpdate(id, { hours: 4 });

// Delete
await Course.findByIdAndDelete(id);
💡
Same shape, real persistence
Notice these routes look almost identical to Lesson 25's array-based CRUD — you're swapping courses.find() for Course.find(), not rewriting your API's structure.
🗒 Cheat Sheet 📝 Worksheet