Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(update): avoid applying defaults on query filter when upserting with empty update #13983

Merged
merged 1 commit into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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');
});
});