backend follow system

πŸ“… 28 Jul 2025

View on Github β†—

date: 2025-07-28 topics: [nodejs, mongodb, social-graph, backend, devflow] day: 12

πŸ“˜ Day 12 – Built a Follow/Unfollow System like Twitter 🧠

βœ… What I Worked On

Today I completed a full Follow/Unfollow feature for DevFlow β€” simulating how apps like Twitter manage social relationships.

FeatureStatus
βž• Follow a userβœ… Done
βž– Unfollow a userβœ… Done
πŸ“ˆ Get followers listβœ… Done
πŸ“‰ Get followings listβœ… Done
🧠 Prevent duplicate followsβœ… Handled

πŸ’‘ How It Works

🧾 MongoDB Schema Design

Each user document includes:

{
  _id: ObjectId,
  username: "sangam",
  followers: [ObjectId],   // who follows you
  following: [ObjectId],   // who you follow
}

πŸ“Œ Updates are atomic using $addToSet (no duplicates) and $pull to remove.

πŸ”„ Follow/Unfollow Logic

  • Follow:

    • Add target user's ID to currentUser.following
    • Add current user ID to targetUser.followers
  • Unfollow:

    • Pull IDs from both arrays

πŸ“¦ Controller Endpoints

  • POST /api/v1/users/:id/follow
  • DELETE /api/v1/users/:id/unfollow
  • GET /api/v1/users/:id/followers
  • GET /api/v1/users/:id/followings

πŸ” Security Notes

  • Middleware ensures user is authenticated
  • Validations prevent self-following or duplicates

πŸ“Έ Snapshot

Follow System Screenshot

❌ Blockers

  • Needed to resolve circular update risk between both users
  • Indexed followers and following fields for faster queries

🧠 Reflection

This may seem like a small feature, but it's core to any social app. I learned how to handle:

  • Mutual updates between collections
  • Preventing duplicate relationships
  • Structuring efficient lookups

β€œSocial graphs are just arrays β€” until you scale them.”

πŸ”œ Next Steps

  • Follow counts cache layer (optional)
  • Show follow button on user profile (frontend)
  • Eventually β†’ notification triggers on follow

πŸ”— References / Code