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(document): make update minimization unset property rather than setting to null #14504

Merged
merged 1 commit into from Apr 7, 2024
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
4 changes: 3 additions & 1 deletion lib/model.js
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
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