Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Testing and Patterns

Discriminators and Schema Inheritance

Model related document types in one collection with Mongoose discriminators - base models, the __t key, extra fields per type, queries across types, embedded discriminators and a runnable stand-in.

Sometimes documents of different kinds belong together. A notification feed holds message, like and follow events. An e-commerce catalog holds book, shirt and laptop products. They share fields (createdAt, owner, title) but each type adds its own (isbn on a book, size on a shirt).

You could make one schema with every field optional, or a collection per type. Mongoose discriminators offer a third way: several models, with different schemas, stored in the same collection, distinguished by a type key. You get inheritance of fields and indexes, per-type validation, and queries across all types at once.

Base model and discriminators

JavaScript
import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const eventSchema = new Schema(
  { owner: { type: Schema.Types.ObjectId, ref: 'User', index: true }, createdAt: { type: Date, default: Date.now } },
  { discriminatorKey: 'kind' },   // default key name is __t
);
const Event = model('Event', eventSchema);

const Message = Event.discriminator('Message', new Schema({ text: { type: String, required: true } }));
const Like    = Event.discriminator('Like',    new Schema({ post: { type: Schema.Types.ObjectId, ref: 'Post' } }));

All documents go in the events collection. A saved message looks like:

JavaScript
{ _id: ..., owner: ..., createdAt: ..., text: 'Hi!', kind: 'Message' }

Mongoose adds the discriminator key (kind here, __t by default) automatically. Each discriminator model:

  • inherits all base fields, indexes, hooks and methods,
  • adds its own fields, validation and methods,
  • automatically filters by its type when you query it.

Queries across and within types

Message.find() runs find({ kind: 'Message' }) for you. Event.find() returns everything, with each result hydrated as the right model (a Message instance for a message, a Like for a like), so instanceof and per-type methods work.

JavaScript
const feed = await Event.find({ owner }).sort({ createdAt: -1 }).limit(20);
for (const e of feed) {
  if (e instanceof Message) show(e.text);
  else if (e instanceof Like) show('liked ' + e.post);
}

Creating through the base model with a type key also works: Event.create({ kind: 'Like', post, owner }) produces a Like. A required rule in a discriminator applies only to documents of that type.

A stand-in for the pattern

The runnable example imitates the idea: one array (the collection), a base shape, per-type validators, and a function that routes each stored document to its type's behavior based on the key.

Node.js One collection, many types (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Indexes with discriminators

All types live in one collection, so indexes defined on the base schema apply to every type. An index declared on a discriminator schema indexes the whole collection, but Mongoose does not add the type filter automatically; make it a partial index if it should only cover one type:

JavaScript
const bookSchema = new Schema({ isbn: String, title: String });
bookSchema.index({ isbn: 1 }, { unique: true, partialFilterExpression: { kind: 'Book' } });

Without the partial filter, every non-book document has isbn: null and the unique index would reject the second one. Lead compound indexes with kind when you often query one type with other filters ({ kind: 1, createdAt: -1 }).

Embedded discriminators

The same idea works inside an array. A page has a list of blocks; each block is text, an image or a button, with different fields:

JavaScript
const pageSchema = new Schema({ title: String, blocks: [new Schema({ order: Number }, { discriminatorKey: 'type' })] });
const blocks = pageSchema.path('blocks');
blocks.discriminator('text',  new Schema({ body: String }));
blocks.discriminator('image', new Schema({ src: String, alt: String }));

Each element validates against its own sub-schema, selected by type. This is a clean way to model polymorphic content with embedded data (see Embedding or referencing).

Node.js Polymorphic blocks (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When to use discriminators

Good fit:

  • Types share most fields and are often queried together (feed, activity log, catalog search across kinds).
  • You want one collection, one set of indexes and simple pagination across all types.
  • The set of types is small and known.

Poor fit:

  • Types share almost nothing: use separate collections.
  • Types have very different volume, indexing or retention needs (a TTL index would expire every type).
  • You need to change a document's type later: it is possible but awkward (update the key and the shape).
  • The hierarchy is deep; keep it one level.

An alternative with no inheritance machinery is a single schema with a type string and a meta Mixed object, but then Mongoose cannot validate type-specific fields. Discriminators give you that validation.

flowchart TB
  B["Event (base schema)<br/>owner, createdAt"] --> M["Message<br/>+ text"]
  B --> L["Like<br/>+ post"]
  B --> F["Follow<br/>+ target"]
  B -. "all stored in" .-> C[("events collection<br/>kind: Message | Like | Follow")]

Subtypes share one collection and a type key.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where are documents of a discriminator model stored?

    All discriminators share the base collection; the discriminator key (default __t) tells them apart.
  2. 2. What does Message.find() do for you automatically?

    A discriminator model adds { kind: 'Message' } (or your key) to its queries.
  3. 3. A unique index on isbn is added in the Book discriminator schema without a partial filter. What goes wrong?

    The index covers the whole shared collection, so use partialFilterExpression on the type key.
  4. 4. Which is a good case for discriminators?

    Shared fields and combined queries are the sweet spot; unrelated or differently managed types fit separate collections.

Summary

  • A discriminator is a model with its own schema stored in the base model's collection.
  • A type key (__t by default, configurable with discriminatorKey) separates the types.
  • Querying the base returns all types, hydrated correctly; querying a discriminator filters by type.
  • Scope indexes with partialFilterExpression and lead with the type key when useful.
  • Embedded discriminators model polymorphic arrays; keep hierarchies shallow.

Next: Project: a blog data layer