Skip to content

Commit

Permalink
fix(model): make Model.validate() static correctly cast document arrays
Browse files Browse the repository at this point in the history
Fix #15164
  • Loading branch information
vkarpov15 committed Jan 8, 2025
1 parent b5752f6 commit 29790cc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -3704,8 +3705,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 29790cc

Please sign in to comment.