Skip to content

Commit

Permalink
Merge pull request #15169 from Automattic/vkarpov15/gh-15164
Browse files Browse the repository at this point in the history
fix(model): make Model.validate() static correctly cast document arrays
  • Loading branch information
vkarpov15 authored Jan 9, 2025
2 parents ad10f48 + 2ee3d06 commit 7ca1847
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3702,8 +3702,9 @@ Model.castObject = function castObject(obj, options) {
Model.castObject.call(schemaType.caster, val)
];
}

continue;
}
continue;
}
if (schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) {
try {
Expand Down
23 changes: 23 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7796,6 +7796,29 @@ describe('Model', function() {
const obj = { sampleArray: { name: 'Taco' } };
assert.throws(() => Test.castObject(obj), /Tried to set nested object field `sampleArray` to primitive value/);
});
it('handles document arrays (gh-15164)', function() {
const barSchema = new mongoose.Schema({
foo: {
type: mongoose.Schema.Types.String,
required: true
}
}, { _id: false });

const fooSchema = new mongoose.Schema({
bars: {
type: [barSchema],
required: true
}
});

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

let obj = Test.castObject({ bars: [] });
assert.deepStrictEqual(obj.bars, []);

obj = Test.castObject({ bars: [{ foo: 'bar' }] });
assert.deepStrictEqual(obj.bars, [{ foo: 'bar' }]);
});
});

it('works if passing class that extends Document to `loadClass()` (gh-12254)', async function() {
Expand Down

0 comments on commit 7ca1847

Please sign in to comment.