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(schema): avoid creating unnecessary clone of schematype in nested array so nested document arrays use correct constructor #14128

Merged
merged 1 commit into from Dec 1, 2023
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
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./
);
});
});