المشروع: التعليقات، و router جُوّه router، وعدد التعليقات

Comment model بيشاور على المنشور وصاحبه. routes/comments.js متركّب على /posts/:id/comments بـ mergeParams علشان يقرا :id. GET بيرجّع comments فيها commentCreator زي Route Posts، و POST بيضيف ويعمل emit. والـ feed بقى فيه commentsCount، محسوب لكل المنشورات مرة واحدة بـ aggregate و $group. وتحدي: deleteComment لصاحب التعليق أو صاحب المنشور.

01 / ملخص الدرس

المشروع: التعليقات، و router جُوّه router، وعدد التعليقات

Comment model بيشاور على المنشور وصاحبه. routes/comments.js متركّب على /posts/:id/comments بـ mergeParams علشان يقرا :id. GET بيرجّع comments فيها commentCreator زي Route Posts، و POST بيضيف ويعمل emit. والـ feed بقى فيه commentsCount، محسوب لكل المنشورات مرة واحدة بـ aggregate و $group. وتحدي: deleteComment لصاحب التعليق أو صاحب المنشور.

02 / شرح الدرس مكتوبًا

نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.

أهلًا بيك. التعليقات. في تطبيق React، صفحة المنشور فيها التعليقات تحته، وكل تعليق فيه صاحبه، وتقدر تكتب تعليق وتمسح تعليقك. والكروت في الـ feed فيها عدد التعليقات. النهارده نبني كل ده. Comment model: post بـ ref، و index علشان هنبحس بيه كتير، و user، و content بحد تلتمية حرف، و likes. و seed.js بقى بيضيف تعليقين على منشور مُنى الأول. الـ schemas: commentBody للكلام، و commentParams: postParams نفسه ومعاه commentId، بـ extend. comments.js، الـ service: toComment: الشكل اللي React مستنيه، وصاحب التعليق اسمه commentCreator، زي Route Posts. findPost: المنشور لازم يبقى موجود، وإلا four oh four. listComments: تعليقات المنشور بس، من الأقدم، بالـ populate والصفحات. addComment: تعمل التعليق، و emit لـ comment colon created ومعاه صاحب المنشور، علشان الإشعارات. و deleteComment لسه بترمي، ودي التحدي.

والـ routes. routes slash comments.js: Router، ومعاه option اسمه mergeParams بـ true. ليه؟ لأننا هنركّبه على slash posts slash colon id slash comments، و colon id دي بتاعة الـ router الأب. من غير mergeParams، req dot params هيبقى فاضي جُوّه الـ router ده. وفي routes slash posts.js بنركّبه بعد requireAuth، فالتعليقات محمية كمان. وآخر حاجة: commentsCount في الـ feed. ممكن نعمل countDocuments لكل منشور، بس ده عشر استعلامات لعشر منشورات. بدله: aggregate، وده أداة MongoDB للحسابات. dollar match: التعليقات اللي على المنشورات دي بس. dollar group: جمّعهم حسب المنشور، و count بـ dollar sum واحد لكل تعليق. استعلام واحد بيرجّع عدد لكل منشور، وبنحطهم في Map علشان نجيبهم بسرعة. نجرب: signin بـ mona، والـ feed بمنشور واحد، والتعليقات عليه، وتعليق جديد.

src/posts.js
import { Post } from "./models/Post.js";
import { User } from "./models/User.js";
import { Comment } from "./models/Comment.js";
import { NotFoundError, ValidationError, ForbiddenError } from "./errors.js";
import { bus } from "./events.js";

const AUTHOR = "name username";

function toPost(post, commentsCount = 0) {
  return {
    _id: post._id,
    body: post.body,
    createdAt: post.createdAt,
    user: post.user,
    likes: post.likes,
    likesCount: post.likes.length,
    commentsCount,
  };
}

export async function listFeed({ page = 1, limit = 10 } = {}) {
  const [posts, total] = await Promise.all([
    Post.find()
      .populate("user", AUTHOR)
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(limit)
      .lean(),
    Post.countDocuments(),
  ]);
  const numberOfPages = Math.max(1, Math.ceil(total / limit));
  const pagination = { currentPage: page, numberOfPages, limit, total };
  if (page < numberOfPages) pagination.nextPage = page + 1;
  const counts = await Comment.aggregate([
    { $match: { post: { $in: posts.map((p) => p._id) } } },
    { $group: { _id: "$post", count: { $sum: 1 } } },
  ]);
  const countOf = new Map(counts.map((c) => [String(c._id), c.count]));
  return { posts: posts.map((p) => toPost(p, countOf.get(String(p._id)) ?? 0)), pagination };
}

export async function getPost(id) {
  const post = await Post.findById(id).populate("user", AUTHOR).lean();
  if (!post) throw new NotFoundError("المنشور");
  return toPost(post, await Comment.countDocuments({ post: id }));
}

export async function createPost({ userId, body }) {
  if (!(await User.exists({ _id: userId }))) throw new ValidationError("المستخدم مش موجود");
  const post = await Post.create({ user: userId, body });
  bus.emit("post:created", post);
  return getPost(post._id);
}

async function findOwnPost(id, userId) {
  const post = await Post.findById(id);
  if (!post) throw new NotFoundError("المنشور");
  if (!post.user.equals(userId)) throw new ForbiddenError("ده مش منشورك");
  return post;
}

export async function updatePost(id, userId, { body }) {
  const post = await findOwnPost(id, userId);
  post.body = body;
  await post.save();
  return getPost(post._id);
}

export async function deletePost(id, userId) {
  const post = await findOwnPost(id, userId);
  await post.deleteOne();
  bus.emit("post:deleted", id);
}

export async function toggleLike(id, userId) {
  const post = await Post.findById(id).select("likes").lean();
  if (!post) throw new NotFoundError("المنشور");

  const liked = !post.likes.some((like) => like.equals(userId));
  await Post.updateOne({ _id: id }, liked ? { $addToSet: { likes: userId } } : { $pull: { likes: userId } });
  if (liked) bus.emit("post:liked", { postId: id, userId });

  const fresh = await getPost(id);
  return { liked, likesCount: fresh.likesCount, post: fresh };
}

المخرجات

$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 96 ms
← 200 OK
{
  "success": true,
  …

→ GET /posts?limit=1  (Authorization: Bearer token)
GET /posts?limit=1 200 - 19 ms
← 200 OK
{
  "success": true,
  "message": "success",
  "data": {
    "posts": [
      {
        "_id": "6ac6a7a6726215dafa93f2cb",
        "body": "أول يوم في الشغل الجديد",
        "createdAt": "2026-10-05T18:00:00.000Z",
        "user": {
          "_id": "6ac6a7a6726215dafa93f2c8",
          "name": "مُنى أحمد",
          "username": "mona"
        },
        "likes": [
          "6ac6a7a6726215dafa93f2c7",
          "6ac6a7a6726215dafa93f2c9"
        ],
        "likesCount": 2,
        "commentsCount": 2
      }
    ]
  …

→ GET /posts/6ac6a7a6726215dafa93f2cb/comments  (Authorization: Bearer token)
GET /posts/6ac6a7a6726215dafa93f2cb/comments 200 - 9 ms
← 200 OK
{
  "success": true,
  "message": "success",
  "data": {
    "comments": [
      {
        "_id": "6ac6a7a6726215dafa93f2d0",
        "content": "مبروك يا مُنى",
        "createdAt": "2026-10-05T18:30:00.000Z",
     
…

الـ feed: commentsCount اتنين. التعليقات: التعليقين من الـ seed، وكل واحد فيه commentCreator بالاسم والـ username. والجديد اتضاف، two oh one. ده بالزبط اللي صفحة المنشور في React بتعرضه.

دورك. والمطلوب بالزبط: deleteComment بتاخد postId و commentId و userId. المنشور لازم يبقى موجود بـ findPost. التعليق لازم يبقى على المنشور ده بالزبط: findOne بالاتنين، ولو مش موجود four oh four. مسموح يمسحه: صاحب التعليق، أو صاحب المنشور، علشان صاحب المنشور يقدر يشيل تعليق مضايق. غير كده four oh three. و deleteOne. اكتب deleteComment.

تمرين

deleteComment: المنشور موجود، والتعليق عليه، ومسموح لصاحب التعليق أو صاحب المنشور، وإلا 403.

الحل. الشرط بـ double pipe: equals مرتين. نجرب: سارة تمسح تعليق محمود على منشور مُنى، وبعدين مُنى تمسحه.

src/comments.js
import { Comment } from "./models/Comment.js";
import { Post } from "./models/Post.js";
import { NotFoundError, ForbiddenError } from "./errors.js";
import { bus } from "./events.js";

const CREATOR = "name username";

function toComment(comment) {
  return {
    _id: comment._id,
    content: comment.content,
    createdAt: comment.createdAt,
    commentCreator: comment.user,
    likes: comment.likes,
    likesCount: comment.likes.length,
  };
}

async function findPost(postId) {
  const post = await Post.findById(postId).select("user").lean();
  if (!post) throw new NotFoundError("المنشور");
  return post;
}

export async function listComments(postId, { page, limit }) {
  await findPost(postId);
  const [comments, total] = await Promise.all([
    Comment.find({ post: postId })
      .populate("user", CREATOR)
      .sort({ createdAt: 1 })
      .skip((page - 1) * limit)
      .limit(limit)
      .lean(),
    Comment.countDocuments({ post: postId }),
  ]);
  const numberOfPages = Math.max(1, Math.ceil(total / limit));
  return { comments: comments.map(toComment), pagination: { currentPage: page, numberOfPages, limit, total } };
}

export async function addComment(postId, userId, content) {
  const post = await findPost(postId);
  const comment = await Comment.create({ post: postId, user: userId, content });
  bus.emit("comment:created", { postId, postOwner: post.user, userId });
  return toComment(await comment.populate("user", CREATOR));
}

export async function deleteComment(postId, commentId, userId) {
  const post = await findPost(postId);
  const comment = await Comment.findOne({ _id: commentId, post: postId });
  if (!comment) throw new NotFoundError("التعليق");
  const allowed = comment.user.equals(userId) || post.user.equals(userId);
  if (!allowed) throw new ForbiddenError("مش مسموح لك تمسح التعليق ده");
  await comment.deleteOne();
}

المخرجات

$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 95 ms
← 200 OK
{
  "success": true,
  …

→ GET /posts?limit=1  (Authorization: Bearer token)
GET /posts?limit=1 200 - 21 ms
← 200 OK
{
  "success": true,
  …

→ GET /posts/6ac6a7a6726215dafa93f2cb/comments  (Authorization: Bearer token)
GET /posts/6ac6a7a6726215dafa93f2cb/comments 200 - 9 ms
← 200 OK
{
  "success": true,
  "message": "success",
  "data": {
    "comments": [
      {
  …

→ POST /users/signin
  {"login":"sara","password":"Social@123"}
POST /users/signin 200 - 70 ms
← 200 OK
{
  "success": true,
  …

→ DELETE /posts/6ac6a7a6726215dafa93f2cb/comments/6ac6a7a6726215dafa93f2d0  (Authorization: Bearer token)
DELETE /posts/6ac6a7a6726215dafa93f2cb/comments/6ac6a7a6726215dafa93f2d0 403 - 7 ms
← 403 Forbidden
{
  "success": false,
  "message": "مش مسموح لك تمسح التعليق ده"
}

→ POST /users/signin
  {"login":"mona","password":"Social@123"}
POST /users/signin 200 - 70 ms
← 200 OK
{
  "success": true,
  …

→ DELETE /posts/6ac6a7a6726215dafa93f2cb/comments/6ac6a7a6726215dafa93f2d0  (Authorization: B
…

سارة four oh three، ومُنى صاحبة المنشور مسحته. الدرس الجاي: حفز المنشورات، و bookmarked لكل مستخدم.

src/models/Comment.js
import mongoose from "mongoose";

const commentSchema = new mongoose.Schema(
  {
    post: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: true, index: true },
    user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
    content: { type: String, required: true, trim: true, maxlength: 300 },
    likes: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
  },
  { timestamps: true },
);

export const Comment = mongoose.model("Comment", commentSchema);
src/routes/posts.js
import { Router } from "express";
import commentsRouter from "./comments.js";
import { listFeed, getPost, createPost, updatePost, deletePost, toggleLike } from "../posts.js";
import { validate } from "../middleware/validate.js";
import { requireAuth } from "../middleware/auth.js";
import { postBody, pageQuery, postParams } from "../schemas/posts.js";

const router = Router();

router.use(requireAuth);
router.use("/:id/comments", commentsRouter);

router.get("/", validate({ query: pageQuery }), async (req, res) => {
  const { posts, pagination } = await listFeed(req.valid.query);
  res.json({ success: true, message: "success", data: { posts }, meta: { pagination } });
});

router.get("/:id", validate({ params: postParams }), async (req, res) => {
  const post = await getPost(req.valid.params.id);
  res.json({ success: true, message: "success", data: { post } });
});

router.post("/", validate({ body: postBody }), async (req, res) => {
  const post = await createPost({ userId: req.user._id, body: req.valid.body.body });
  res.status(201).json({ success: true, message: "اتنشر", data: { post } });
});

router.put("/:id", validate({ params: postParams, body: postBody }), async (req, res) => {
  const post = await updatePost(req.valid.params.id, req.user._id, req.valid.body);
  res.json({ success: true, message: "اتعدل", data: { post } });
});

router.delete("/:id", validate({ params: postParams }), async (req, res) => {
  await deletePost(req.valid.params.id, req.user._id);
  res.json({ success: true, message: "اتمسح", data: {} });
});

router.put("/:id/like", validate({ params: postParams }), async (req, res) => {
  const result = await toggleLike(req.valid.params.id, req.user._id);
  res.json({ success: true, message: result.liked ? "عملت إعجاب" : "شلت الإعجاب", data: result });
});

export default router;
src/schemas/posts.js
import { z } from "zod";

const MAX = Number(process.env.MAX_POST_LENGTH ?? 500);

export const postBody = z.object({
  body: z.string({ error: "المنشور لازم يبقى نص" }).trim().min(1, "المنشور فاضي").max(MAX, `المنشور أطول من ${MAX} حرف`),
});

export const pageQuery = z.object({
  page: z.coerce.number({ error: "رقم الصفحة لازم يبقى رقم" }).int().min(1).default(1),
  limit: z.coerce.number({ error: "الـ limit لازم يبقى رقم" }).int().min(1).max(50).default(10),
});

export const postParams = z.object({
  id: z.string().regex(/^[a-f\d]{24}$/i, "الـ id مش صحيح"),
});

export const commentBody = z.object({
  content: z.string({ error: "التعليق لازم يبقى نص" }).trim().min(1, "التعليق فاضي").max(300, "التعليق أطول من 300 حرف"),
});

export const commentParams = postParams.extend({
  commentId: z.string().regex(/^[a-f\d]{24}$/i, "الـ id بتاع التعليق مش صحيح"),
});
seed.js
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
import { User } from "./src/models/User.js";
import { Post } from "./src/models/Post.js";
import { Comment } from "./src/models/Comment.js";

await mongoose.connect(process.env.MONGO_URI);
await Promise.all([User.deleteMany({}), Post.deleteMany({}), Comment.deleteMany({})]);

// Every seeded user signs in with Social@123.
const password = await bcrypt.hash("Social@123", 10);
const [mahmoud, mona, karim, sara] = await User.insertMany([
  { name: "محمود مجدي", username: "mahmoud", email: "[email protected]", password, gender: "male" },
  { name: "مُنى أحمد", username: "mona", email: "[email protected]", password, gender: "female" },
  { name: "كريم سامي", username: "karim", email: "[email protected]", password, gender: "male" },
  { name: "سارة علي", username: "sara", email: "[email protected]", password, gender: "female" },
]);

const at = (iso) => new Date(iso);
const [first] = await Post.insertMany([
  { user: mona._id, body: "أول يوم في الشغل الجديد", likes: [mahmoud._id, karim._id], createdAt: at("2026-10-05T18:00:00Z") },
  { user: karim._id, body: "خلصت أول مشروع React ليا", likes: [mona._id], createdAt: at("2026-10-05T15:30:00Z") },
  { user: mahmoud._id, body: "مين بيحب يذاكر بالليل؟", likes: [mona._id, karim._id, sara._id], createdAt: at("2026-10-05T11:00:00Z") },
  { user: sara._id, body: "صورة من رحلة إسكندرية", likes: [], createdAt: at("2026-10-04T20:00:00Z") },
  { user: mona._id, body: "القهوة الصبح دي أهم من أي حاجة", likes: [mahmoud._id], createdAt: at("2026-10-03T08:00:00Z") },
]);

await Comment.insertMany([
  { post: first._id, user: mahmoud._id, content: "مبروك يا مُنى", createdAt: at("2026-10-05T18:30:00Z") },
  { post: first._id, user: karim._id, content: "ربنا يوفقك", createdAt: at("2026-10-05T19:00:00Z") },
]);

console.log(`الـ seed خلص: ${await User.countDocuments()} مستخدمين و ${await Post.countDocuments()} منشورات`);
await mongoose.disconnect();
src/routes/comments.js
import { Router } from "express";
import { listComments, addComment, deleteComment } from "../comments.js";
import { validate } from "../middleware/validate.js";
import { commentBody, commentParams, pageQuery, postParams } from "../schemas/posts.js";

// mergeParams: the :id of the post comes from the parent router (/posts/:id/comments).
const router = Router({ mergeParams: true });

router.get("/", validate({ params: postParams, query: pageQuery }), async (req, res) => {
  const { comments, pagination } = await listComments(req.valid.params.id, req.valid.query);
  res.json({ success: true, message: "success", data: { comments }, meta: { pagination } });
});

router.post("/", validate({ params: postParams, body: commentBody }), async (req, res) => {
  const comment = await addComment(req.valid.params.id, req.user._id, req.valid.body.content);
  res.status(201).json({ success: true, message: "اتضاف التعليق", data: { comment } });
});

router.delete("/:commentId", validate({ params: commentParams }), async (req, res) => {
  await deleteComment(req.valid.params.id, req.valid.params.commentId, req.user._id);
  res.json({ success: true, message: "اتمسح التعليق", data: {} });
});

export default router;
03 / دروس الكورس (70)
  1. 01أهلًا بيك: هنبني إيه في الكورس ده
  2. 02يعني إيه Node.js؟ وأول برنامج برة المتصفح
  3. 03process.argv: برنامج بياخد معلومات من الأمر نفسه
  4. 04Environment variables: إعدادات برة الـ code
  5. 05تقسيم الـ code على ملفات: require و module.exports
  6. 06ES modules: import و export، والنظام اللي هنبني بيه المشروع
  7. 07الـ modules اللي جاية مع Node: path و os و crypto
  8. 08المشروع: بداية Social API، والبيانات اللي هنشتغل عليها
  9. 09قراية وكتابة الملفات: fs بالطريقة المتزامنة
  10. 10ليه Node بيحب الـ async: fs.readFile و callbacks
  11. 11fs/promises و async/await: نفس الـ async من غير callback hell
  12. 12ملفات JSON: نخزن objects و arrays ونرجعهم
  13. 13الـ folders: mkdir و readdir و stat و rm
  14. 14المشروع: أول database لـ Social على ملفات JSON
  15. 15blocking: لما الـ thread الواحد يقف، كل حاجة تقف
  16. 16الـ event loop: مين بيشتغل إمتى
  17. 17الـ promises من جُوّه: new Promise و resolve و reject
  18. 18Promise.all وأخواتها: كذا حاجة في نفس الوقت
  19. 19الأخطاء في الـ async: await المنسية، والخطأ اللي بيوقّع البرنامج
  20. 20المشروع: Promise.all، و race condition بيضيّع منشور، وطابور للكتابة
  21. 21الـ events: EventEmitter و on و emit
  22. 22الـ streams: ملف كبير حتة حتة
  23. 23pipeline: نوصّل الـ streams ببعض، ونضغط ونفلتر
  24. 24الـ terminal نفسه stream: process.stdout و readline
  25. 25المشروع: أداة command line، و events بتسجل النشاط في stream
  26. 26npm و package.json: بطاقة المشروع والـ scripts
  27. 27npm install: نستخدم package حد تاني كتبها
  28. 28المشروع: package.json و scripts و .gitignore و .env
  29. 29HTTP، وأول server بـ node:http
  30. 30الـ routing بإيدينا: method و path و query و params
  31. 31نستقبل body: الـ request نفسه stream
  32. 32المشروع: Social API على node:http من غير مكتبات
  33. 33Express: نفس الـ server في نص الـ code
  34. 34POST و PATCH و DELETE في Express، و express.json
  35. 35الـ middleware: function في نص الطريق
  36. 36Router: كل مجموعة routes في ملف
  37. 37الأخطاء في Express: throw في أي route، ورد واحد من مكان واحد
  38. 38المشروع: Social API على Express، بترتيب المشاريع الحقيقية
  39. 39ملفات ثابتة بـ express.static، و CORS علشان React يكلمنا
  40. 40Zod على الـ server: ما تصدقش أي حاجة جاية من برة
  41. 41middleware واحد للـ validation في كل الـ routes
  42. 42المشروع: Zod في Social API، و pagination زي Route Posts
  43. 43MongoDB: قاعدة بيانات بتخزن documents
  44. 44Mongoose: Schema و Model بيحددوا شكل البيانات
  45. 45القراية من MongoDB: find والشروط والترتيب والصفحات
  46. 46التعديل والمسح: $set و $inc و $addToSet و $pull
  47. 47العلاقات: ref و populate
  48. 48المشروع: Social API على MongoDB
  49. 49كلمات السر: ليه ما بنحفزهاش، و bcrypt
  50. 50JWT: الـ server يفتكرك إزاي
  51. 51المشروع: حساب جديد، بـ Zod و bcrypt و MongoDB
  52. 52المشروع: تسجيل الدخول، ونرجّع token
  53. 53المشروع: middleware بيحمي الـ routes بالـ token
  54. 54المشروع: الصلاحيات، منشورك بس اللي تعدّله
  55. 55المشروع: تغيير كلمة السر، والـ tokens القديمة تبطل
  56. 56المشروع: نفس شكل Route Posts، والإعجاب
  57. 57المشروع: التعليقات، و router جُوّه router، وعدد التعليقاتانت هنا
  58. 58المشروع: حفظ المنشورات، و bookmarked لكل مستخدم
  59. 59المشروع: المتابعة، وصفحة الـ profile
  60. 60المشروع: feed الناس اللي بتتابعهم، والاقتراحات
  61. 61المشروع: الإشعارات من الـ events
  62. 62رفع الملفات بـ multer
  63. 63المشروع: منشورات بصور، بنفس الـ FormData اللي React بيبعتها
  64. 64الأمان: helmet و CORS و rate limiting
  65. 65الإعدادات: environment variables متفحوصة من أول ثانية
  66. 66الاختبارات بـ node:test
  67. 67اختبار الـ API كله: supertest وقاعدة بيانات للاختبار
  68. 68المشروع: نربط تطبيق React بالـ API بتاعنا
  69. 69النشر: MongoDB Atlas و Render
  70. 70الخلاصة، وإيه الخطوة الجاية