From d783c0388b609d05011f2e9740b6f50c677b2d8c Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 11 Aug 2023 10:52:37 -0400 Subject: [PATCH] fix(query): allow deselecting discriminator key Fix #13679 --- lib/queryhelpers.js | 2 +- test/query.test.js | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/queryhelpers.js b/lib/queryhelpers.js index 6c90b39fae4..b07c1f884cc 100644 --- a/lib/queryhelpers.js +++ b/lib/queryhelpers.js @@ -325,7 +325,7 @@ exports.applyPaths = function applyPaths(fields, schema) { // If set to 0, we're explicitly excluding the discriminator key. Can't do this for all fields, // because we have tests that assert that using `-path` to exclude schema-level `select: true` // fields counts as an exclusive projection. See gh-11546 - if (exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) { + if (!exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) { delete fields[path]; return; } diff --git a/test/query.test.js b/test/query.test.js index ad7fcd2caed..13dbd36177b 100644 --- a/test/query.test.js +++ b/test/query.test.js @@ -4170,4 +4170,15 @@ describe('Query', function() { await q.exec(); assert.equal(q.op, 'findOneAndReplace'); }); + + it('allows deselecting discriminator key (gh-13679)', async function() { + const testSchema = new Schema({ name: String }); + const Test = db.model('Test', testSchema); + const Test2 = Test.discriminator('Test2', new Schema({ test: String })); + + const { _id } = await Test2.create({ name: 'test1', test: 'test2' }); + const { name, __t } = await Test.findById(_id).select({ __t: 0 }); + assert.strictEqual(name, 'test1'); + assert.strictEqual(__t, undefined); + }); });