ውሂብ (Data) ን ቋሚ ቦታ ማስቀመጫ — Database! 🔥
Store your data permanently! MongoDB = NoSQL Database, Mongoose = ODM for Node.js!
ክፍል 15 ውስጥ users ን array ውስጥ ሰቀልን — Server ሲቋረጥ ሁሉም ይጠፋሉ! Database = ውሂብ ቋሚ ቦታ ይቀመጣል — Server ቢዘጋ አይጠፋም!
In Lesson 15 we stored data in an array — it disappears on restart! Database = permanent, persistent storage!
📊 SQL Database vs MongoDB — ልዩነቱ ምንድን ነው?
| SQL (MySQL) | MongoDB 🍃 | ምን ማለት ነው? |
|---|---|---|
| Table | Collection | ውሂብ የሚቀመጥበት ቦታ |
| Row | Document | አንድ record (user, product...) |
| Column | Field | አንድ property (name, age...) |
| Schema strict | Flexible schema | MongoDB documents ሊለያዩ ይችላሉ! |
| SQL language | JSON-like queries | MongoDB JS ይመስላል! |
MongoDB ውሂብን JSON format ሆኖ ያስቀምጣል — JavaScript object ይመስላል! ሁሉም document የራሱ _id (unique ID) አለው!
MongoDB stores data as JSON-like documents — looks just like a JavaScript object! Auto-generated _id is unique!
Mongoose = MongoDB + Node.js ን ቀላሉን አቋራጭ! Schema ይሰራል፣ Validation ያደርጋል፣ CRUD operations ቀለል ያደርጋቸዋል!
Mongoose is an ODM (Object Document Mapper) — it adds structure, validation and easy methods to MongoDB!
ምሳሌ: MongoDB = ፋይል ካቢኔ | Mongoose = ፋይሉን የሚያስተዳድር ሠራተኛ — ፋይሉ format አለው፣ ቁጥጥር አለው!
MongoDB is the filing cabinet. Mongoose is the librarian who organizes, validates, and retrieves files for you!
// Terminal ውስጥ: // npm install mongoose const mongoose = require('mongoose'); // MongoDB Atlas (cloud) ወይም local ጋር ተያያዝ mongoose.connect('mongodb://localhost:27017/ethiocode') .then(() => console.log('🍃 MongoDB Connected!')) .catch(err => console.log('Error:', err)); // ethiocode = database ስም (ካሌ ቢሆን ራሱ ይፈጥረዋል)
// ── Schema — Document ቅርጽ ይወስናል ───────────── const userSchema = new mongoose.Schema({ name: { type: String, required: true, // ግዴታ — ስም ያስፈልጋል! trim: true, // ፊት ኋላ space ያስወጣ }, email: { type: String, required: true, unique: true, // አንድ email አንድ ጊዜ ብቻ! lowercase: true, // ሁሌ lowercase ያደርጋል }, age: { type: Number, min: 0, // 0 በታች አይፈቀድም max: 120, }, role: { type: String, enum: ['user', 'admin'], // ሁለቱ ብቻ ይፈቀዳሉ! default: 'user', // default = user }, skills: [String], // String array createdAt: { type: Date, default: Date.now, // ራሱ ጊዜ ያስቀምጣል }, }); // ── Model — Schema ን ወደ usable class ─────────── const User = mongoose.model('User', userSchema); // 'User' → MongoDB ውስጥ 'users' collection ይሆናል module.exports = User;
const express = require('express'); const router = express.Router(); const User = require('../models/User'); // ── GET /api/users — ሁሉም users ───────────────── router.get('/', async (req, res) => { try { const users = await User.find().sort({ createdAt: -1 }); res.json({ success: true, count: users.length, data: users }); } catch (err) { res.status(500).json({ error: err.message }); } }); // ── POST /api/users — አዲስ user ────────────────── router.post('/', async (req, res) => { try { const user = await User.create(req.body); // Mongoose Schema validation ራሱ ያረጋግጣል! res.status(201).json({ success: true, data: user }); } catch (err) { res.status(400).json({ error: err.message }); } }); // ── PUT /api/users/:id — user ቀይር ────────────── router.put('/:id', async (req, res) => { try { const user = await User .findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if (!user) return res.status(404).json({ error: 'Not found' }); res.json({ success: true, data: user }); } catch (err) { res.status(400).json({ error: err.message }); } }); // ── DELETE /api/users/:id ──────────────────────── router.delete('/:id', async (req, res) => { try { await User.findByIdAndDelete(req.params.id); res.json({ success: true, message: 'User deleted!' }); } catch (err) { res.status(500).json({ error: err.message }); } }); module.exports = router;
MongoDB Collection simulator! Create, Read, Update, Delete — ሙሉ CRUD ሞክር! Real MongoDB ይመስላል! 🔥
Simulate MongoDB operations — add documents, query, update and delete — just like the real thing!
// ── ሁሉም users ───────────────────────────────── await User.find(); // ── filter — role = admin ─────────────────────── await User.find({ role: 'admin' }); // ── ከ 18 ዕድሜ በላይ ────────────────────────────── await User.find({ age: { $gte: 18 } }); // $gte = >= | $gt = > | $lt = < | $lte = <= // ── ስም ፈልግ (search) ──────────────────────────── await User.find({ name: { $regex: 'Abel', $options: 'i' } }); // ── Sort + Limit + Select ─────────────────────── await User .find({ role: 'user' }) .sort({ createdAt: -1 }) // ቅርብ ቀን ፊት .limit(10) // 10 ብቻ .select('name email'); // name + email ብቻ ስጥ // ── Count ── ──────────────────────────────────── await User.countDocuments({ role: 'admin' }); // ── findOne — አንዱን ብቻ ───────────────────────── await User.findOne({ email: 'abel@ethiocode.com' });
Array ውስጥ ያለ ውሂብ Server ሲዘጋ ይጠፋል — Database ቋሚ ነው! MongoDB = NoSQL, JSON-like!
Without a database, all data is lost on server restart. MongoDB persists it permanently.
Table→Collection | Row→Document | Column→Field — JSON format ሆኖ ያስቀምጣል!
MongoDB stores data as flexible JSON documents — no rigid table structure needed!
Schema = document ምን fields ይኖሩት፣ type ምን ይሁን፣ required ነው? validation ሁሉ!
Schema defines the shape of documents and handles validation automatically.
Create→User.create() | Read→User.find() | Update→findByIdAndUpdate() | Delete→findByIdAndDelete()
Four operations cover everything — create, read, update, delete any data.
React (Frontend) → Express API → MongoDB (Database) — ሙሉ MERN Stack!
MERN = MongoDB + Express + React + Node.js — the most popular full stack combo!