Skip to content

Commit

Permalink
fix(update): avoid applying defaults on query filter when upserting w…
Browse files Browse the repository at this point in the history
…ith empty update

Fix #13962
  • Loading branch information
vkarpov15 committed Oct 16, 2023
1 parent 236a7a7 commit e44e75b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/helpers/query/castUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
Object.keys(filter).length > 0) {
// Trick the driver into allowing empty upserts to work around
// https://github.com/mongodb/node-mongodb-native/pull/2490
return { $setOnInsert: filter };
// Shallow clone to avoid passing defaults in re: gh-13962
return { $setOnInsert: { ...filter } };
}
return ret;
};
Expand Down
17 changes: 17 additions & 0 deletions test/model.findOneAndUpdate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2200,4 +2200,21 @@ describe('model: findOneAndUpdate:', function() {
assert.ok(document);
assert.equal(document.name, 'test');
});

it('skips adding defaults to filter when passing empty update (gh-13962)', async function() {
const schema = new Schema({
myField: Number,
defaultField: { type: String, default: 'default' }
}, { versionKey: false });
const Test = db.model('Test', schema);

await Test.create({ myField: 1, defaultField: 'some non-default value' });

const updated = await Test.findOneAndUpdate(
{ myField: 1 },
{},
{ upsert: true, returnDocument: 'after' }
);
assert.equal(updated.defaultField, 'some non-default value');
});
});

0 comments on commit e44e75b

Please sign in to comment.