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:

  1. Base Schema (common fields)
  2. 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