Skip to content

Commit

Permalink
Merge pull request #12390 from Automattic/vkarpov15/gh-12279
Browse files Browse the repository at this point in the history
fix(setDefaultsOnInsert): avoid applying defaults on insert if nested property set
  • Loading branch information
vkarpov15 committed Sep 7, 2022
2 parents 5db3c3e + 3aebf81 commit 9939664
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/helpers/setDefaultsOnInsert.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ function isModified(modified, path) {
if (modified[path]) {
return true;
}

// Is any parent path of `path` modified?
const sp = path.split('.');
let cur = sp[0];
for (let i = 1; i < sp.length; ++i) {
Expand All @@ -113,5 +115,18 @@ function isModified(modified, path) {
}
cur += '.' + sp[i];
}

// Is any child of `path` modified?
const modifiedKeys = Object.keys(modified);
if (modifiedKeys.length) {
const parentPath = path + '.';

for (const modifiedPath of modifiedKeys) {
if (modifiedPath.slice(0, path.length + 1) === parentPath) {
return true;
}
}
}

return false;
}
21 changes: 21 additions & 0 deletions test/helpers/setDefaultsOnInsert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,25 @@ describe('setDefaultsOnInsert', function() {

assert.equal(update.$setOnInsert['time.resolved'], 42);
});

it('skips default if parent is $set (gh-12279)', function() {
const SubscriptionsConfigSchema = Schema({
hasPaidSubscription: { type: Boolean, required: true },
hasPastDueInvoice: { type: Boolean, required: true }
});

const CustomerSchema = Schema({
subscriptionsConfig: {
type: SubscriptionsConfigSchema,
required: true,
default: { hasPaidSubscription: false, hasPastDueInvoice: false }
}
});

const opts = {};
let update = { $set: { 'subscriptionsConfig.hasPaidSubscription': 100 } };
update = setDefaultsOnInsert({}, CustomerSchema, update, opts);

assert.ok(!update.$setOnInsert);
});
});

0 comments on commit 9939664

Please sign in to comment.