• [

    The model.discriminator() function

    ](#the-model-discriminator-function)

  • [

    Discriminators save to the Event model’s collection

    ](#discriminators-save-to-the-event-models-collection)

  • [

    Discriminator keys

    ](#discriminator-keys)

  • [

    Discriminators add the discriminator key to queries

    ](#discriminators-add-the-discriminator-key-to-queries)

  • [

    Discriminators copy pre and post hooks

    ](#discriminators-copy-pre-and-post-hooks)

  • [

    Handling custom _id fields

    ](#handling-custom-_id-fields)

  • [

    Using discriminators with Model.create()

    ](#using-discriminators-with-model-create)

  • [

    Embedded discriminators in arrays

    ](#embedded-discriminators-in-arrays)

  • [

    Recursive embedded discriminators in arrays

    ](#recursive-embedded-discriminators-in-arrays)

  • [

    Single nested discriminators

    ](#single-nested-discriminators)

[

The model.discriminator() function

](#the-model-discriminator-function)

Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.

Suppose you wanted to track different types of events in a single collection. Every event will have a timestamp, but events that represent clicked links should have a URL. You can achieve this using the model.discriminator() function. This function takes 3 parameters, a model name, a discriminator schema and an optional key (defaults to the model name). It returns a model whose schema is the union of the base schema and the discriminator schema.

  1. const options = { discriminatorKey: 'kind' };
  2. const eventSchema = new mongoose.Schema({ time: Date }, options);
  3. const Event = mongoose.model('Event', eventSchema);
  4. // ClickedLinkEvent is a special type of Event that has
  5. // a URL.
  6. const ClickedLinkEvent = Event.discriminator('ClickedLink',
  7. new mongoose.Schema({ url: String }, options));
  8. // When you create a generic event, it can't have a URL field...
  9. const genericEvent = new Event({ time: Date.now(), url: 'google.com' });
  10. assert.ok(!genericEvent.url);
  11. // But a ClickedLinkEvent can
  12. const clickedEvent =
  13. new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
  14. assert.ok(clickedEvent.url);

[

Discriminators save to the Event model’s collection

](#discriminators-save-to-the-event-models-collection)

Suppose you created another discriminator to track events where a new user registered. These SignedUpEvent instances will be stored in the same collection as generic events and ClickedLinkEvent instances.

  1. const event1 = new Event({ time: Date.now() });
  2. const event2 = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
  3. const event3 = new SignedUpEvent({ time: Date.now(), user: 'testuser' });
  4. /*
  5. const save = function(doc, callback) {
  6. doc.save(function(error, doc) {
  7. callback(error, doc);
  8. });
  9. }; */
  10. Promise.all([event1.save(), event2.save(), event3.save()]).
  11. then(() => Event.countDocuments()).
  12. then(count => {
  13. assert.equal(count, 3);
  14. });

[

Discriminator keys

](#discriminator-keys)

The way mongoose tells the difference between the different discriminator models is by the ‘discriminator key’, which is __t by default. Mongoose adds a String path called __t to your schemas that it uses to track which discriminator this document is an instance of.

  1. const event1 = new Event({ time: Date.now() });
  2. const event2 = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
  3. const event3 = new SignedUpEvent({ time: Date.now(), user: 'testuser' });
  4. assert.ok(!event1.__t);
  5. assert.equal(event2.__t, 'ClickedLink');
  6. assert.equal(event3.__t, 'SignedUp');

[

Discriminators add the discriminator key to queries

](#discriminators-add-the-discriminator-key-to-queries)

Discriminator models are special; they attach the discriminator key to queries. In other words, find(), count(), aggregate(), etc. are smart enough to account for discriminators.

  1. const event1 = new Event({ time: Date.now() });
  2. const event2 = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
  3. const event3 = new SignedUpEvent({ time: Date.now(), user: 'testuser' });
  4. Promise.all([event1.save(), event2.save(), event3.save()]).
  5. then(() => ClickedLinkEvent.find({})).
  6. then(docs => {
  7. assert.equal(docs.length, 1);
  8. assert.equal(docs[0]._id.toString(), event2._id.toString());
  9. assert.equal(docs[0].url, 'google.com');
  10. });

[

Discriminators copy pre and post hooks

](#discriminators-copy-pre-and-post-hooks)

Discriminators also take their base schema’s pre and post middleware. However, you can also attach middleware to the discriminator schema without affecting the base schema.

  1. const options = { discriminatorKey: 'kind' };
  2. const eventSchema = new mongoose.Schema({ time: Date }, options);
  3. let eventSchemaCalls = 0;
  4. eventSchema.pre('validate', function(next) {
  5. ++eventSchemaCalls;
  6. next();
  7. });
  8. const Event = mongoose.model('GenericEvent', eventSchema);
  9. const clickedLinkSchema = new mongoose.Schema({ url: String }, options);
  10. let clickedSchemaCalls = 0;
  11. clickedLinkSchema.pre('validate', function(next) {
  12. ++clickedSchemaCalls;
  13. next();
  14. });
  15. const ClickedLinkEvent = Event.discriminator('ClickedLinkEvent',
  16. clickedLinkSchema);
  17. const event1 = new ClickedLinkEvent();
  18. event1.validate(function() {
  19. assert.equal(eventSchemaCalls, 1);
  20. assert.equal(clickedSchemaCalls, 1);
  21. const generic = new Event();
  22. generic.validate(function() {
  23. assert.equal(eventSchemaCalls, 2);
  24. assert.equal(clickedSchemaCalls, 1);
  25. });
  26. });

[

Handling custom _id fields

](#handling-custom-_id-fields)

A discriminator’s fields are the union of the base schema’s fields and the discriminator schema’s fields, and the discriminator schema’s fields take precedence. There is one exception: the _id field. If a custom _id field is set on the base schema, that will always override the discriminator’s _id field, as shown below.

  1. const options = { discriminatorKey: 'kind' };
  2. // Base schema has a custom String `_id` and a Date `time`...
  3. const eventSchema = new mongoose.Schema({ _id: String, time: Date },
  4. options);
  5. const Event = mongoose.model('BaseEvent', eventSchema);
  6. const clickedLinkSchema = new mongoose.Schema({
  7. url: String,
  8. time: String
  9. }, options);
  10. // The discriminator schema has a String `time` and an
  11. // implicitly added ObjectId `_id`.
  12. assert.ok(clickedLinkSchema.path('_id'));
  13. assert.equal(clickedLinkSchema.path('_id').instance, 'ObjectID');
  14. const ClickedLinkEvent = Event.discriminator('ChildEventBad',
  15. clickedLinkSchema);
  16. const event1 = new ClickedLinkEvent({ _id: 'custom id', time: '4pm' });
  17. // clickedLinkSchema overwrites the `time` path, but **not**
  18. // the `_id` path.
  19. assert.strictEqual(typeof event1._id, 'string');
  20. assert.strictEqual(typeof event1.time, 'string');

[

Using discriminators with Model.create()

](#using-discriminators-with-model-create)

When you use Model.create(), mongoose will pull the correct type from the discriminator key for you.

  1. const Schema = mongoose.Schema;
  2. const shapeSchema = new Schema({
  3. name: String
  4. }, { discriminatorKey: 'kind' });
  5. const Shape = db.model('Shape', shapeSchema);
  6. const Circle = Shape.discriminator('Circle',
  7. new Schema({ radius: Number }));
  8. const Square = Shape.discriminator('Square',
  9. new Schema({ side: Number }));
  10. const shapes = [
  11. { name: 'Test' },
  12. { kind: 'Circle', radius: 5 },
  13. { kind: 'Square', side: 10 }
  14. ];
  15. Shape.create(shapes, function(error, shapes) {
  16. assert.ifError(error);
  17. assert.ok(shapes[0] instanceof Shape);
  18. assert.ok(shapes[1] instanceof Circle);
  19. assert.equal(shapes[1].radius, 5);
  20. assert.ok(shapes[2] instanceof Square);
  21. assert.equal(shapes[2].side, 10);
  22. });

[

Embedded discriminators in arrays

](#embedded-discriminators-in-arrays)

You can also define discriminators on embedded document arrays. Embedded discriminators are different because the different discriminator types are stored in the same document array (within a document) rather than the same collection. In other words, embedded discriminators let you store subdocuments matching different schemas in the same array.

As a general best practice, make sure you declare any hooks on your schemas before you use them. You should not call pre() or post() after calling discriminator()

  1. const eventSchema = new Schema({ message: String },
  2. { discriminatorKey: 'kind', _id: false });
  3. const batchSchema = new Schema({ events: [eventSchema] });
  4. // `batchSchema.path('events')` gets the mongoose `DocumentArray`
  5. const docArray = batchSchema.path('events');
  6. // The `events` array can contain 2 different types of events, a
  7. // 'clicked' event that requires an element id that was clicked...
  8. const clickedSchema = new Schema({
  9. element: {
  10. type: String,
  11. required: true
  12. }
  13. }, { _id: false });
  14. // Make sure to attach any hooks to `eventSchema` and `clickedSchema`
  15. // **before** calling `discriminator()`.
  16. const Clicked = docArray.discriminator('Clicked', clickedSchema);
  17. // ... and a 'purchased' event that requires the product that was purchased.
  18. const Purchased = docArray.discriminator('Purchased', new Schema({
  19. product: {
  20. type: String,
  21. required: true
  22. }
  23. }, { _id: false }));
  24. const Batch = db.model('EventBatch', batchSchema);
  25. // Create a new batch of events with different kinds
  26. const batch = {
  27. events: [
  28. { kind: 'Clicked', element: '#hero', message: 'hello' },
  29. { kind: 'Purchased', product: 'action-figure-1', message: 'world' }
  30. ]
  31. };
  32. Batch.create(batch).
  33. then(function(doc) {
  34. assert.equal(doc.events.length, 2);
  35. assert.equal(doc.events[0].element, '#hero');
  36. assert.equal(doc.events[0].message, 'hello');
  37. assert.ok(doc.events[0] instanceof Clicked);
  38. assert.equal(doc.events[1].product, 'action-figure-1');
  39. assert.equal(doc.events[1].message, 'world');
  40. assert.ok(doc.events[1] instanceof Purchased);
  41. doc.events.push({ kind: 'Purchased', product: 'action-figure-2' });
  42. return doc.save();
  43. }).
  44. then(function(doc) {
  45. assert.equal(doc.events.length, 3);
  46. assert.equal(doc.events[2].product, 'action-figure-2');
  47. assert.ok(doc.events[2] instanceof Purchased);
  48. done();
  49. }).
  50. catch(done);

[

Recursive embedded discriminators in arrays

](#recursive-embedded-discriminators-in-arrays)

You can also define embedded discriminators on embedded discriminators. In the below example, sub_events is an embedded discriminator, and for sub_event keys with value ‘SubEvent’, sub_events.events is an embedded discriminator.

  1. const singleEventSchema = new Schema({ message: String },
  2. { discriminatorKey: 'kind', _id: false });
  3. const eventListSchema = new Schema({ events: [singleEventSchema] });
  4. const subEventSchema = new Schema({
  5. sub_events: [singleEventSchema]
  6. }, { _id: false });
  7. const SubEvent = subEventSchema.path('sub_events').
  8. discriminator('SubEvent', subEventSchema);
  9. eventListSchema.path('events').discriminator('SubEvent', subEventSchema);
  10. const Eventlist = db.model('EventList', eventListSchema);
  11. // Create a new batch of events with different kinds
  12. const list = {
  13. events: [
  14. { kind: 'SubEvent', sub_events: [{ kind: 'SubEvent', sub_events: [], message: 'test1' }], message: 'hello' },
  15. { kind: 'SubEvent', sub_events: [{ kind: 'SubEvent', sub_events: [{ kind: 'SubEvent', sub_events: [], message: 'test3' }], message: 'test2' }], message: 'world' }
  16. ]
  17. };
  18. Eventlist.create(list).
  19. then(function(doc) {
  20. assert.equal(doc.events.length, 2);
  21. assert.equal(doc.events[0].sub_events[0].message, 'test1');
  22. assert.equal(doc.events[0].message, 'hello');
  23. assert.ok(doc.events[0].sub_events[0] instanceof SubEvent);
  24. assert.equal(doc.events[1].sub_events[0].sub_events[0].message, 'test3');
  25. assert.equal(doc.events[1].message, 'world');
  26. assert.ok(doc.events[1].sub_events[0].sub_events[0] instanceof SubEvent);
  27. doc.events.push({ kind: 'SubEvent', sub_events: [{ kind: 'SubEvent', sub_events: [], message: 'test4' }], message: 'pushed' });
  28. return doc.save();
  29. }).
  30. then(function(doc) {
  31. assert.equal(doc.events.length, 3);
  32. assert.equal(doc.events[2].message, 'pushed');
  33. assert.ok(doc.events[2].sub_events[0] instanceof SubEvent);
  34. done();
  35. }).
  36. catch(done);

[

Single nested discriminators

](#single-nested-discriminators)

You can also define discriminators on single nested subdocuments, similar to how you can define discriminators on arrays of subdocuments.

As a general best practice, make sure you declare any hooks on your schemas before you use them. You should not call pre() or post() after calling discriminator()

  1. const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  2. const schema = Schema({ shape: shapeSchema });
  3. schema.path('shape').discriminator('Circle', Schema({ radius: String }));
  4. schema.path('shape').discriminator('Square', Schema({ side: Number }));
  5. const MyModel = mongoose.model('ShapeTest', schema);
  6. // If `kind` is set to 'Circle', then `shape` will have a `radius` property
  7. let doc = new MyModel({ shape: { kind: 'Circle', radius: 5 } });
  8. doc.shape.radius; // 5
  9. // If `kind` is set to 'Square', then `shape` will have a `side` property
  10. doc = new MyModel({ shape: { kind: 'Square', side: 10 } });
  11. doc.shape.side; // 10