Skip to content

Commit

Permalink
Merge pull request #12797 from lpizzinidev/gh-12794
Browse files Browse the repository at this point in the history
fix(query): update queries removes fields set to `undefined`
  • Loading branch information
vkarpov15 committed Dec 16, 2022
2 parents 0ed6e71 + 99b6cca commit ff67167
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/helpers/query/castUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
const op = ops[i];
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 &&
typeof val === 'object' &&
Expand All @@ -100,6 +106,10 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {

if (op.startsWith('$') && utils.isEmptyObject(val)) {
delete ret[op];
if (op === '$set' && !utils.isEmptyObject(toUnset)) {
// Unset all undefined values
ret['$unset'] = toUnset;
}
}
}

Expand Down
26 changes: 26 additions & 0 deletions test/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4313,4 +4313,30 @@ describe('Query', function() {
assert.strictEqual(found.length, 1);
assert.strictEqual(found[0].title, 'burrito bowl');
});

it('update operation should remove fields set to undefined (gh-12794)', async() => {
const m = new mongoose.Mongoose();

await m.connect(start.uri);

const schema = new mongoose.Schema({ title: String });

const Test = m.model('test', schema);

const doc = await Test.create({
title: 'test'
});

assert.strictEqual(doc.title, 'test');

const updatedDoc = await Test.findOneAndUpdate(
{
_id: doc._id
},
{ title: undefined },
{ returnOriginal: false }
).lean();

assert.ok('title' in updatedDoc === false);
});
});

0 comments on commit ff67167

Please sign in to comment.