Skip to content

Commit

Permalink
Merge pull request #14151 from Automattic/vkarpov15/gh-14058
Browse files Browse the repository at this point in the history
fix: avoid minimizing single nested subdocs if they are required
  • Loading branch information
vkarpov15 committed Dec 5, 2023
2 parents 2d65e00 + c752f40 commit fda0a1c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/helpers/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function clone(obj, options, isArrayChild) {
ret = obj.toObject(options);
}

if (options && options.minimize && isSingleNested && Object.keys(ret).length === 0) {
if (options && options.minimize && !obj.constructor.$__required && isSingleNested && Object.keys(ret).length === 0) {
return undefined;
}

Expand Down
5 changes: 3 additions & 2 deletions lib/schema/SubdocumentPath.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function SubdocumentPath(schema, path, options) {

schema = handleIdOption(schema, options);

this.caster = _createConstructor(schema);
this.caster = _createConstructor(schema, null, options);
this.caster.path = path;
this.caster.prototype.$basePath = path;
this.schema = schema;
Expand All @@ -69,7 +69,7 @@ SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions;
* ignore
*/

function _createConstructor(schema, baseClass) {
function _createConstructor(schema, baseClass, options) {
// lazy load
Subdocument || (Subdocument = require('../types/subdocument'));

Expand All @@ -89,6 +89,7 @@ function _createConstructor(schema, baseClass) {
_embedded.prototype = Object.create(proto);
_embedded.prototype.$__setSchema(schema);
_embedded.prototype.constructor = _embedded;
_embedded.$__required = options?.required;
_embedded.base = schema.base;
_embedded.schema = schema;
_embedded.$isSingleNested = true;
Expand Down
11 changes: 11 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,17 @@ describe('document', function() {
assert.strictEqual(myModel.toObject().foo, void 0);
});

it('does not minimize single nested subdocs if they are required (gh-14058) (gh-11247)', async function() {
const nestedSchema = Schema({ bar: String }, { _id: false });
const schema = Schema({ foo: { type: nestedSchema, required: true } });

const MyModel = db.model('Test', schema);

const myModel = await MyModel.create({ foo: {} });

assert.deepStrictEqual(myModel.toObject().foo, {});
});

it('should propogate toObject to implicitly created schemas (gh-13599) (gh-13325)', async function() {
const transformCalls = [];
const userSchema = Schema({
Expand Down

0 comments on commit fda0a1c

Please sign in to comment.