From 29790cc56649b57e25948a53e5aed614e0aa1dc9 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 8 Jan 2025 14:27:19 -0500 Subject: [PATCH] fix(model): make Model.validate() static correctly cast document arrays Fix #15164 --- lib/model.js | 4 +++- test/model.test.js | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index 67ccfb83a6..db5410a20e 100644 --- a/lib/model.js +++ b/lib/model.js @@ -3667,6 +3667,7 @@ Model.castObject = function castObject(obj, options) { const val = get(obj, path); pushNestedArrayPaths(paths, val, path); } + console.log('AB', obj, paths); let error = null; @@ -3704,8 +3705,9 @@ Model.castObject = function castObject(obj, options) { Model.castObject.call(schemaType.caster, val) ]; } + + continue; } - continue; } if (schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) { try { diff --git a/test/model.test.js b/test/model.test.js index e6a1ef9cd3..af518fe734 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -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() {