Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow defining index on base model that applies to all discriminators #14176

Merged
merged 2 commits into from Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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