Skip to content

Commit

Permalink
fix(schema): avoid creating unnecessary clone of schematype in nested…
Browse files Browse the repository at this point in the history
… array so nested document arrays use correct constructor

Fix #14101
  • Loading branch information
vkarpov15 committed Nov 29, 2023
1 parent d31310a commit 4817c60
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
7 changes: 3 additions & 4 deletions lib/schema.js
Expand Up @@ -1122,15 +1122,14 @@ Schema.prototype.path = function(path, obj) {
if (_schemaType.$isMongooseDocumentArray) {
_schemaType.$embeddedSchemaType._arrayPath = arrayPath;
_schemaType.$embeddedSchemaType._arrayParentPath = path;
_schemaType = _schemaType.$embeddedSchemaType.clone();
_schemaType = _schemaType.$embeddedSchemaType;
} else {
_schemaType.caster._arrayPath = arrayPath;
_schemaType.caster._arrayParentPath = path;
_schemaType = _schemaType.caster.clone();
_schemaType = _schemaType.caster;
}

_schemaType.path = arrayPath;
toAdd.push(_schemaType);
this.subpaths[arrayPath] = _schemaType;
}

for (const _schemaType of toAdd) {
Expand Down
24 changes: 24 additions & 0 deletions test/types.documentarray.test.js
Expand Up @@ -754,4 +754,28 @@ describe('types.documentarray', function() {

assert.equal(doc.myMap.get('foo').$path(), 'myMap.foo');
});

it('bubbles up validation errors from doubly nested doc arrays (gh-14101)', async function() {
const optionsSchema = new mongoose.Schema({
val: {
type: Number,
required: true
}
});

const testSchema = new mongoose.Schema({
name: String,
options: {
type: [[optionsSchema]],
required: true
}
});

const Test = db.model('Test', testSchema);

await assert.rejects(
Test.create({ name: 'test', options: [[{ val: null }]] }),
/options.0.0.val: Path `val` is required./
);
});
});

0 comments on commit 4817c60

Please sign in to comment.