Skip to content

Commit

Permalink
Merge pull request #14176 from peplin/discriminator-existence-on-index
Browse files Browse the repository at this point in the history
Allow defining index on base model that applies to all discriminators
  • Loading branch information
vkarpov15 committed Dec 21, 2023
2 parents aa4b38a + 909c773 commit 9c17773
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/helpers/indexes/getRelatedIndexes.js
@@ -1,5 +1,7 @@
'use strict';

const hasDollarKeys = require('../query/hasDollarKeys');

function getRelatedSchemaIndexes(model, schemaIndexes) {
return getRelatedIndexes({
baseModelName: model.baseModelName,
Expand Down Expand Up @@ -46,7 +48,9 @@ function getRelatedIndexes({

return indexes.filter(index => {
const partialFilterExpression = getPartialFilterExpression(index, indexesType);
return !partialFilterExpression || !partialFilterExpression[discriminatorKey];
return !partialFilterExpression
|| !partialFilterExpression[discriminatorKey]
|| (hasDollarKeys(partialFilterExpression[discriminatorKey]) && !('$eq' in partialFilterExpression[discriminatorKey]));
});
}

Expand Down
40 changes: 40 additions & 0 deletions test/helpers/indexes.getRelatedIndexes.test.js
Expand Up @@ -92,6 +92,46 @@ describe('getRelatedIndexes', () => {
]
);
});
it('with base model that has discriminator, it includes discriminator indexes that only checks for existence', () => {
// Arrange
const eventSchema = new Schema(
{ actorId: { type: Schema.Types.ObjectId } },
{ autoIndex: false }
);
eventSchema.index({ actorId: 1 },
{ unique: true,
partialFilterExpression: {
__t: { $exists: true }
}
});

const Event = db.model('Event', eventSchema);

const clickEventSchema = new Schema(
{
clickedAt: Date,
productCategory: String
},
{ autoIndex: false }
);
Event.discriminator('ClickEvent', clickEventSchema);

// Act
const filteredSchemaIndexes = getRelatedSchemaIndexes(Event, Event.schema.indexes());

// Assert
assert.deepStrictEqual(
filteredSchemaIndexes,
[
[{ actorId: 1 },
{ background: true,
unique: true,
partialFilterExpression: { __t: { $exists: true } }
}
]
]
);
});
it('with discriminator model, it only gets discriminator indexes', () => {
// Arrange
const eventSchema = new Schema(
Expand Down

0 comments on commit 9c17773

Please sign in to comment.