Skip to content

Commit

Permalink
fix(aggregate): avoid adding extra $match stage if user manually se…
Browse files Browse the repository at this point in the history
…t discriminator key to correct value in first pipeline stage

Fix #12478
  • Loading branch information
vkarpov15 committed Oct 19, 2022
1 parent e519505 commit c798368
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/helpers/aggregate/prepareDiscriminatorPipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ module.exports = function prepareDiscriminatorPipeline(pipeline, schema, prefix)
// If the first pipeline stage is a match and it doesn't specify a `__t`
// key, add the discriminator key to it. This allows for potential
// aggregation query optimizations not to be disturbed by this feature.
if (originalPipeline[0] != null && originalPipeline[0].$match && !originalPipeline[0].$match[filterKey]) {
if (originalPipeline[0] != null &&
originalPipeline[0].$match &&
(originalPipeline[0].$match[filterKey] === undefined || originalPipeline[0].$match[filterKey] === discriminatorValue)) {
originalPipeline[0].$match[filterKey] = discriminatorValue;
// `originalPipeline` is a ref, so there's no need for
// aggregate._pipeline = originalPipeline
Expand Down
30 changes: 30 additions & 0 deletions test/helpers/aggregate.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const assert = require('assert');
const prepareDiscriminatorPipeline = require('../../lib/helpers/aggregate/prepareDiscriminatorPipeline');
const stringifyFunctionOperators = require('../../lib/helpers/aggregate/stringifyFunctionOperators');

describe('stringifyFunctionOperators', function() {
Expand Down Expand Up @@ -63,3 +64,32 @@ describe('stringifyFunctionOperators', function() {
assert.equal(typeof pipeline[0].$addFields.newField.$function.body, 'string');
});
});

describe('prepareDiscriminatorPipeline', function() {
it('handles case where initial $match includes the discriminator key (gh-12478)', function() {
const pipeline = [
{
$match: {
partition: 'Child',
$text: {
$search: 'test'
}
}
}
];
const fakeSchema = { discriminatorMapping: { isRoot: false, key: 'partition', value: 'Child' } };

prepareDiscriminatorPipeline(pipeline, fakeSchema);

assert.deepStrictEqual(pipeline, [
{
$match: {
partition: 'Child',
$text: {
$search: 'test'
}
}
}
]);
});
});

0 comments on commit c798368

Please sign in to comment.