Skip to content

Commit

Permalink
Allow defining index on base model that applies to all discriminators
Browse files Browse the repository at this point in the history
  • Loading branch information
peplin committed Dec 13, 2023
1 parent aa4b38a commit e0b9eed
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/helpers/indexes/getRelatedIndexes.js
Expand Up @@ -46,7 +46,9 @@ function getRelatedIndexes({

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

Expand Down
36 changes: 36 additions & 0 deletions test/helpers/indexes.getRelatedIndexes.test.js
Expand Up @@ -92,6 +92,42 @@ 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} } }]

Check failure on line 127 in test/helpers/indexes.getRelatedIndexes.test.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

A space is required after '{'

Check failure on line 127 in test/helpers/indexes.getRelatedIndexes.test.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

A space is required before '}'
]
);
});
it('with discriminator model, it only gets discriminator indexes', () => {
// Arrange
const eventSchema = new Schema(
Expand Down

0 comments on commit e0b9eed

Please sign in to comment.