Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

20. MongoDB Models for Like, Playlist and Tweet

Lesson 20 of 23 in the free Backend Development notes on Siksha Sarovar, written by Rohit Jangra.

Like Schema — Polymorphic Design

A "like" in our application can be applied to three different types of content: videos, comments, and tweets. Instead of creating three separate schemas (VideoLike, CommentLike, TweetLike), we use a polymorphic design with optional reference fields:

const likeSchema = new Schema(
  {
    likedBy: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    video: { type: Schema.Types.ObjectId, ref: 'Video' },
    comment: { type: Schema.Types.ObjectId, ref: 'Comment' },
    tweet: { type: Schema.Types.ObjectId, ref: 'Tweet' },
  },
  { timestamps: true }
);

Each Like document has exactly one of the optional fields populated. A like on a video has video set. A like on a comment has comment set. A like on a tweet has tweet set.

Why not use refPath (dynamic reference)?

refPath is MongoDB's built-in polymorphic reference:

{
  onModel: { type: String, enum: ['Video', 'Comment', 'Tweet'] },
  onDocument: { type: Schema.Types.ObjectId, refPath: 'onModel' }
}

Both approaches work, but the three optional fields approach is more explicit and easier to query. With separate fields, indexing is straightforward and querying likes for a specific video is simply Like.find({ video: videoId }).

---

Like Schema Indexes

// Unique: a user can only like a video/comment/tweet once
likeSchema.index({ likedBy: 1, video: 1 }, { unique: true, sparse: true });
likeSchema.index({ likedBy: 1, comment: 1 }, { unique: true, sparse: true });
likeSchema.index({ likedBy: 1, tweet: 1 }, { unique: true, sparse: true });
// sparse: true means the index only includes documents where the field exists

---

Playlist Schema

A playlist contains an ordered list of videos and belongs to a user:

const playlistSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    description: { type: String, default: '' },
    videos: [{ type: Schema.Types.ObjectId, ref: 'Video' }],
    owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    isPublic: { type: Boolean, default: true },
  },
  { timestamps: true }
);

playlistSchema.index({ owner: 1 });

Operations:

  • Add video: $addToSet (prevents duplicates) → { $addToSet: { videos: videoId } }
  • Remove video: $pull{ $pull: { videos: videoId } }

---

Tweet Schema

Tweets are short text posts (similar to Twitter):

const tweetSchema = new Schema(
  {
    content: {
      type: String,
      required: [true, 'Tweet content is required'],
      trim: true,
      maxlength: [280, 'Tweet cannot exceed 280 characters'],
    },
    owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  },
  { timestamps: true }
);

tweetSchema.index({ owner: 1, createdAt: -1 });

---

Virtual Populate for Like Count on Video

Instead of storing likeCount as a field on the Video document (which would require updating it on every like/unlike), use a virtual populate to compute it on demand:

// On Video schema:
videoSchema.virtual('likeCount', {
  ref: 'Like',
  localField: '_id',
  foreignField: 'video',
  count: true,   // Returns count instead of array of documents
});

// Usage:
const video = await Video.findById(id).populate('likeCount');
console.log(video.likeCount);  // Number

For the profile to be consistent, also need:

videoSchema.set('toJSON', { virtuals: true });
videoSchema.set('toObject', { virtuals: true });

---

Why These Designs Are Flexible and Scalable

Design DecisionBenefit
Polymorphic likes (3 optional fields)Single schema handles 3 content types
Sparse unique indexes on likesEnforce uniqueness without wasting index space on null fields
$addToSet for playlist videosAutomatic deduplication at the database level
Tweet maxlength: 280Character limit enforced at schema level
Virtual populate for countsCount computed on demand, no stale count data
{ owner: 1, createdAt: -1 } index on tweetsFast "get user's tweets, newest first" query

---

Aggregation Counts vs Virtual Populate vs Denormalised Count

ApproachWhen to UseProsCons
Aggregation (real-time)Complex queries combining count + other dataAlways accurateAggregation overhead per request
Virtual populateSimple count on demandClean APIExtra DB query
Denormalised count fieldHigh-read, low-write scenariosFastest readsRisk of stale data, must update atomically

For a YouTube-like app with many concurrent likes, a real-time aggregation count is safest. For a low-volume system, virtual populate is simplest.