Discriminators
๐น What are Discriminators?
Discriminators allow you to store different types of documents in the same collection using a base schema.
๐ Think of it like:
- One collection
- Multiple document types
๐ Used when documents are similar but have some different fields
๐น Why Use Discriminators?
- Avoid creating multiple collections
- Reuse common fields
- Keep data organized
๐น Basic Idea
You create:
- Base Schema (common fields)
- Child Schemas (extra fields)
๐น Example
๐ Base Schema (Vehicle)
const mongoose = require("mongoose")
const options = { discriminatorKey: "type" }
const vehicleSchema = new mongoose.Schema({
brand: String
}, options)
const Vehicle = mongoose.model("Vehicle", vehicleSchema)
๐ Child Schema (Car)
const carSchema = new mongoose.Schema({
doors: Number
})
const Car = Vehicle.discriminator("Car", carSchema)
๐ Child Schema (Bike)
const bikeSchema = new mongoose.Schema({
hasCarrier: Boolean
})
const Bike = Vehicle.discriminator("Bike", bikeSchema)
๐น How Data Looks in DB
All stored in same collection (vehicles):
Document 1:
type: "Car", brand: "Toyota", doors: 4
Document 2:
type: "Bike", brand: "Hero", hasCarrier: true
๐น discriminatorKey
๐ Field that tells which type of document it is
Example:
type: "Car" or "Bike"
(Default key is __t if not specified)
๐น When to Use
Use discriminators when:
- Data shares common structure
- But has some differences
๐ Examples:
- Payment methods (card, UPI, cash)
- Vehicles (car, bike)
- Users (admin, customer)
๐ฅ Simple Understanding
๐ One collection + multiple document types
๐ Shared base + specific fields