diff --git a/lib/helpers/aggregate/prepareDiscriminatorPipeline.js b/lib/helpers/aggregate/prepareDiscriminatorPipeline.js index d06e8d70dde..f720cfb6c28 100644 --- a/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +++ b/lib/helpers/aggregate/prepareDiscriminatorPipeline.js @@ -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 diff --git a/test/helpers/aggregate.test.js b/test/helpers/aggregate.test.js index 9c10444f7bf..95684d8fca6 100644 --- a/test/helpers/aggregate.test.js +++ b/test/helpers/aggregate.test.js @@ -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() { @@ -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' + } + } + } + ]); + }); +});