From 1cbe8e8c00183e5185c1ada483cd54d456295beb Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 22 Dec 2022 17:33:52 -0500 Subject: [PATCH] fix(query): fix unexpected validation error when doing findOneAndReplace() with a nullish value --- lib/helpers/query/castUpdate.js | 8 +++++--- test/query.test.js | 12 +++++++++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/helpers/query/castUpdate.js b/lib/helpers/query/castUpdate.js index 50d56509610..2e1dde1a6c0 100644 --- a/lib/helpers/query/castUpdate.js +++ b/lib/helpers/query/castUpdate.js @@ -85,9 +85,11 @@ module.exports = function castUpdate(schema, obj, options, context, filter) { val = ret[op]; hasDollarKey = hasDollarKey || op.startsWith('$'); const toUnset = {}; - for (const key of Object.keys(val)) { - if (val[key] === undefined) { - toUnset[key] = 1; + if (val != null) { + for (const key of Object.keys(val)) { + if (val[key] === undefined) { + toUnset[key] = 1; + } } } diff --git a/test/query.test.js b/test/query.test.js index f291c5d226f..a02a37896d0 100644 --- a/test/query.test.js +++ b/test/query.test.js @@ -4314,7 +4314,7 @@ describe('Query', function() { assert.strictEqual(found[0].title, 'burrito bowl'); }); - it('update operation should remove fields set to undefined (gh-12794)', async() => { + it('update operation should remove fields set to undefined (gh-12794) (gh-12821)', async function() { const m = new mongoose.Mongoose(); await m.connect(start.uri); @@ -4338,5 +4338,15 @@ describe('Query', function() { ).lean(); assert.ok('title' in updatedDoc === false); + + const replacedDoc = await Test.findOneAndReplace( + { + _id: doc._id + }, + { title: undefined }, + { returnOriginal: false } + ).lean(); + + assert.ok('title' in replacedDoc === false); }); });