Skip to content

Commit 7ca1847

Browse files
authored
Merge pull request #15169 from Automattic/vkarpov15/gh-15164
fix(model): make Model.validate() static correctly cast document arrays
2 parents ad10f48 + 2ee3d06 commit 7ca1847

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/model.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3702,8 +3702,9 @@ Model.castObject = function castObject(obj, options) {
37023702
Model.castObject.call(schemaType.caster, val)
37033703
];
37043704
}
3705+
3706+
continue;
37053707
}
3706-
continue;
37073708
}
37083709
if (schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) {
37093710
try {

test/model.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7796,6 +7796,29 @@ describe('Model', function() {
77967796
const obj = { sampleArray: { name: 'Taco' } };
77977797
assert.throws(() => Test.castObject(obj), /Tried to set nested object field `sampleArray` to primitive value/);
77987798
});
7799+
it('handles document arrays (gh-15164)', function() {
7800+
const barSchema = new mongoose.Schema({
7801+
foo: {
7802+
type: mongoose.Schema.Types.String,
7803+
required: true
7804+
}
7805+
}, { _id: false });
7806+
7807+
const fooSchema = new mongoose.Schema({
7808+
bars: {
7809+
type: [barSchema],
7810+
required: true
7811+
}
7812+
});
7813+
7814+
const Test = db.model('Test', fooSchema);
7815+
7816+
let obj = Test.castObject({ bars: [] });
7817+
assert.deepStrictEqual(obj.bars, []);
7818+
7819+
obj = Test.castObject({ bars: [{ foo: 'bar' }] });
7820+
assert.deepStrictEqual(obj.bars, [{ foo: 'bar' }]);
7821+
});
77997822
});
78007823

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

0 commit comments

Comments
 (0)