The Code Fix

🍃 شرح MongoDB

MongoDB مع Node.js

Mongoose

أشهر مكتبة للتعامل مع MongoDB من Node.js، تضيف بنية ونماذج منظّمة:

npm install mongoose

الاتصال

import mongoose from "mongoose";

await mongoose.connect("mongodb://localhost:27017/mydb");
console.log("متّصل بقاعدة البيانات");

تعريف نموذج (Schema)

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  age: Number,
  email: { type: String, unique: true },
});

const User = mongoose.model("User", userSchema);

العمليات

// إنشاء
const user = await User.create({ name: "براء", age: 25 });

// قراءة
const users = await User.find();
const one = await User.findById(id);

// تعديل
await User.findByIdAndUpdate(id, { age: 26 });

// حذف
await User.findByIdAndDelete(id);

مثال كامل مع Express

app.get("/users", async (req, res) => {
  const users = await User.find();
  res.json(users);
});

app.post("/users", async (req, res) => {
  const user = await User.create(req.body);
  res.status(201).json(user);
});

💡 هذا هو "MERN/MEAN stack" الشهير: MongoDB + Express + (React/Angular) + Node — كله بلغة JavaScript.

🎉 أكملت أساسيات MongoDB! أصبحت قادرًا على بناء تطبيقات بقواعد بيانات NoSQL. اختبر نفسك واحصل على شهادتك.