Skip to content

Commit fda0a1c

Browse files
authored
Merge pull request #14151 from Automattic/vkarpov15/gh-14058
fix: avoid minimizing single nested subdocs if they are required
2 parents 2d65e00 + c752f40 commit fda0a1c

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

lib/helpers/clone.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ function clone(obj, options, isArrayChild) {
5454
ret = obj.toObject(options);
5555
}
5656

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

lib/schema/SubdocumentPath.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ function SubdocumentPath(schema, path, options) {
4848

4949
schema = handleIdOption(schema, options);
5050

51-
this.caster = _createConstructor(schema);
51+
this.caster = _createConstructor(schema, null, options);
5252
this.caster.path = path;
5353
this.caster.prototype.$basePath = path;
5454
this.schema = schema;
@@ -69,7 +69,7 @@ SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions;
6969
* ignore
7070
*/
7171

72-
function _createConstructor(schema, baseClass) {
72+
function _createConstructor(schema, baseClass, options) {
7373
// lazy load
7474
Subdocument || (Subdocument = require('../types/subdocument'));
7575

@@ -89,6 +89,7 @@ function _createConstructor(schema, baseClass) {
8989
_embedded.prototype = Object.create(proto);
9090
_embedded.prototype.$__setSchema(schema);
9191
_embedded.prototype.constructor = _embedded;
92+
_embedded.$__required = options?.required;
9293
_embedded.base = schema.base;
9394
_embedded.schema = schema;
9495
_embedded.$isSingleNested = true;

test/document.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,17 @@ describe('document', function() {
793793
assert.strictEqual(myModel.toObject().foo, void 0);
794794
});
795795

796+
it('does not minimize single nested subdocs if they are required (gh-14058) (gh-11247)', async function() {
797+
const nestedSchema = Schema({ bar: String }, { _id: false });
798+
const schema = Schema({ foo: { type: nestedSchema, required: true } });
799+
800+
const MyModel = db.model('Test', schema);
801+
802+
const myModel = await MyModel.create({ foo: {} });
803+
804+
assert.deepStrictEqual(myModel.toObject().foo, {});
805+
});
806+
796807
it('should propogate toObject to implicitly created schemas (gh-13599) (gh-13325)', async function() {
797808
const transformCalls = [];
798809
const userSchema = Schema({

0 commit comments

Comments
 (0)