Skip to content

Commit

Permalink
fix(model): make subclassed models handle discriminators correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Mar 7, 2019
1 parent fa662ee commit a465059
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const VERSION_ALL = VERSION_WHERE | VERSION_INC;
const modelCollectionSymbol = Symbol.for('mongoose#Model#collection');
const modelSymbol = require('./helpers/symbols').modelSymbol;
const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
const subclassedSymbol = Symbol('mongoose#Model#subclassed');

/**
* A Model is a class that's your primary tool for interacting with MongoDB.
Expand Down Expand Up @@ -1027,6 +1028,14 @@ Model.discriminator = function(name, schema, value) {
applyMethods(d, schema);
applyStatics(d, schema);

if (this[subclassedSymbol] != null) {
for (const submodel of this[subclassedSymbol]) {
submodel.discriminators = submodel.discriminators || {};
submodel.discriminators[name] =
model.__subclass(model.db, schema, submodel.collection.name);
}
}

return d;
};

Expand Down Expand Up @@ -4656,6 +4665,16 @@ Model.__subclass = function subclass(conn, schema, collection) {
Model.prototype.__proto__ = _this.prototype;
Model.db = Model.prototype.db = conn;

_this[subclassedSymbol] = _this[subclassedSymbol] || [];
_this[subclassedSymbol].push(Model);
if (_this.discriminators != null) {
Model.discriminators = {};
for (const key of Object.keys(_this.discriminators)) {
Model.discriminators[key] = _this.discriminators[key].
__subclass(_this.db, _this.discriminators[key].schema, collection);
}
}

const s = schema && typeof schema !== 'string'
? schema
: _this.prototype.schema;
Expand Down

0 comments on commit a465059

Please sign in to comment.