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 2 parameters, a model name and a discriminator schema. It returns a model whose schema is the union of the base schema and the discriminator schema.

    1. var options = {discriminatorKey: 'kind'};
    2. var eventSchema = new mongoose.Schema({time: Date}, options);
    3. var Event = mongoose.model('Event', eventSchema);
    4. // ClickedLinkEvent is a special type of Event that has
    5. // a URL.
    6. var 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. var genericEvent = new Event({time: Date.now(), url: 'google.com'});
    10. assert.ok(!genericEvent.url);
    11. // But a ClickedLinkEvent can
    12. var clickedEvent =
    13. new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
    14. assert.ok(clickedEvent.url);

    Discriminators save to the Event model’s 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. var event1 = new Event({time: Date.now()});
    2. var event2 = new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
    3. var event3 = new SignedUpEvent({time: Date.now(), user: 'testuser'});
    4. var save = function (doc, callback) {
    5. doc.save(function (error, doc) {
    6. callback(error, doc);
    7. });
    8. };
    9. async.map([event1, event2, event3], save, function (error) {
    10. Event.count({}, function (error, count) {
    11. assert.equal(count, 3);
    12. });
    13. });

    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. var event1 = new Event({time: Date.now()});
    2. var event2 = new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
    3. var 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

    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. var event1 = new Event({time: Date.now()});
    2. var event2 = new ClickedLinkEvent({time: Date.now(), url: 'google.com'});
    3. var event3 = new SignedUpEvent({time: Date.now(), user: 'testuser'});
    4. var save = function (doc, callback) {
    5. doc.save(function (error, doc) {
    6. callback(error, doc);
    7. });
    8. };
    9. async.map([event1, event2, event3], save, function (error) {
    10. ClickedLinkEvent.find({}, function (error, docs) {
    11. assert.equal(docs.length, 1);
    12. assert.equal(docs[0]._id.toString(), event2._id.toString());
    13. assert.equal(docs[0].url, 'google.com');
    14. });
    15. });

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

    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 default _id field.

    You can work around this by setting the _id option to false in the discriminator schema as shown below.

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

    Using discriminators with Model.create()

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

    1. var Schema = mongoose.Schema;
    2. var shapeSchema = new Schema({
    3. name: String
    4. }, { discriminatorKey: 'kind' });
    5. var Shape = db.model('Shape', shapeSchema);
    6. var Circle = Shape.discriminator('Circle',
    7. new Schema({ radius: Number }));
    8. var Square = Shape.discriminator('Square',
    9. new Schema({ side: Number }));
    10. var 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

    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. var eventSchema = new Schema({ message: String },
    2. { discriminatorKey: 'kind', _id: false });
    3. var batchSchema = new Schema({ events: [eventSchema] });
    4. // `batchSchema.path('events')` gets the mongoose `DocumentArray`
    5. var 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. var 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. var Clicked = docArray.discriminator('Clicked', clickedSchema);
    17. // ... and a 'purchased' event that requires the product that was purchased.
    18. var Purchased = docArray.discriminator('Purchased', new Schema({
    19. product: {
    20. type: String,
    21. required: true
    22. }
    23. }, { _id: false }));
    24. var Batch = db.model('EventBatch', batchSchema);
    25. // Create a new batch of events with different kinds
    26. var 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

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