var options = {discriminatorKey:'kind'};var eventSchema =newmongoose.Schema({time: Date}, options);var Event =mongoose.model('Event', eventSchema);// ClickedLinkEvent is a special type of Event that has// a URL.var ClickedLinkEvent =Event.discriminator('ClickedLink',newmongoose.Schema({url: String}, options));// When you create a generic event, it can't have a URL field...var genericEvent =newEvent({time:Date.now(), url:'google.com'});assert.ok(!genericEvent.url);// But a ClickedLinkEvent canvar clickedEvent =newClickedLinkEvent({time:Date.now(), url:'google.com'});assert.ok(clickedEvent.url);
var options = {discriminatorKey:'kind'};// Base schema has a String _id...var eventSchema =newmongoose.Schema({_id: String, time: Date}, options);var Event =mongoose.model('BaseEvent', eventSchema);var clickedLinkSchema =newmongoose.Schema({url: String}, options);var ClickedLinkEvent =Event.discriminator('ChildEventBad', clickedLinkSchema);var event1 =newClickedLinkEvent();// Woops, clickedLinkSchema overwrote the custom _idassert.ok(event1._id instanceofmongoose.Types.ObjectId);// But if you set `_id` option to false... clickedLinkSchema =newmongoose.Schema({url: String}, {discriminatorKey:'kind', _id:false}); ClickedLinkEvent =Event.discriminator('ChildEventGood', clickedLinkSchema);// The custom _id from the base schema comes throughvar event2 =newClickedLinkEvent({_id:'test'});assert.ok(event2._id.toString() ===event2._id);