QA
Beginner LevelMongoDB & Mongoose

What are Mongoose Discriminators and how do they enable schema inheritance?

❓ Interview Prompt: Explain Mongoose Discriminators, Single Table Inheritance pattern, discriminatorKey (__t), and polymorphism.

Mongoose Discriminators implement schema inheritance, allowing multiple models with distinct schema fields to share a single underlying MongoDB collection:

How It Works:

Injects a discriminatorKey (default '__t') into documents, storing the model type name. Queries automatically scope to specific discriminator schemas!

Code Implementation Example

typescript
import { Schema, model } from 'mongoose';

const options = { discriminatorKey: 'kind', collection: 'events' };
const eventSchema = new Schema({ timestamp: Date }, options);
const EventModel = model('Event', eventSchema);

// ClickEvent discriminator inheriting from EventModel
const ClickEventModel = EventModel.discriminator('ClickEvent', new Schema({
  elementId: String
}));
💡Implementing schema inheritance using Mongoose discriminators.
🎯 Interview Key Takeaway

Use Mongoose discriminators to store polymorphic models with shared base properties in a single collection.

#Discriminators#Inheritance#Polymorphism#Mongoose#Beginner
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?