Skip to content

Commit

Permalink
Merge pull request #14504 from Automattic/vkarpov15/gh-14445
Browse files Browse the repository at this point in the history
fix(document): make update minimization unset property rather than setting to null
  • Loading branch information
vkarpov15 authored Apr 7, 2024
2 parents eb2a52e + 1adf0e0 commit bb2eb40
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
4 changes: 3 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,9 @@ Model.prototype.$__handleSave = function(options, callback) {
}
minimize(updateOp[key]);
if (Object.keys(updateOp[key]).length === 0) {
updateOp[key] = null;
delete updateOp[key];
update.$unset = update.$unset || {};
update.$unset[key] = 1;
}
}
}
Expand Down
37 changes: 34 additions & 3 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13060,8 +13060,8 @@ describe('document', function() {
x.metadata = {};
await x.save();

const { metadata } = await Model.findById(m._id).orFail();
assert.strictEqual(metadata, null);
const { metadata } = await Model.findById(m._id).lean().orFail();
assert.strictEqual(metadata, undefined);
});

it('saves when setting subdocument to empty object (gh-14420) (gh-13782)', async function() {
Expand All @@ -13085,7 +13085,7 @@ describe('document', function() {
await doc.save();

const savedDoc = await MainModel.findById(doc.id).orFail();
assert.strictEqual(savedDoc.sub, null);
assert.strictEqual(savedDoc.sub, undefined);
});

it('validate supports validateAllPaths', async function() {
Expand Down Expand Up @@ -13205,6 +13205,37 @@ describe('document', function() {
err.errors['docArr.0.subprop'].message
);
});

it('minimize unsets property rather than setting to null (gh-14445)', async function() {
const SubSchema = new mongoose.Schema({
name: { type: String }
}, { _id: false });

const MainSchema = new mongoose.Schema({
name: String,
sub: {
type: SubSchema,
default: {}
}
});

const Test = db.model('Test', MainSchema);
const doc = new Test({ name: 'foo' });
await doc.save();

const savedDocFirst = await Test.findById(doc.id).orFail();
assert.deepStrictEqual(savedDocFirst.toObject({ minimize: false }).sub, {});

savedDocFirst.name = 'bar';
await savedDocFirst.save();

const lean = await Test.findById(doc.id).lean().orFail();
assert.strictEqual(lean.sub, undefined);

const savedDocSecond = await Test.findById(doc.id).orFail();
assert.deepStrictEqual(savedDocSecond.toObject({ minimize: false }).sub, {});

});
});

describe('Check if instance function that is supplied in schema option is availabe', function() {
Expand Down

0 comments on commit bb2eb40

Please sign in to comment.