Skip to content

Commit 682160f

Browse files
authored
Merge pull request Automattic#15124 from Automattic/vkarpov15/Automatticgh-15075-2
fix(model): handle document array paths set to non-array values in Model.castObject()
2 parents bbca321 + dfd96dc commit 682160f

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

lib/model.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ const util = require('util');
6969
const utils = require('./utils');
7070
const minimize = require('./helpers/minimize');
7171
const MongooseBulkSaveIncompleteError = require('./error/bulkSaveIncompleteError');
72+
const ObjectExpectedError = require('./error/objectExpected');
7273

7374
const modelCollectionSymbol = Symbol('mongoose#Model#collection');
7475
const modelDbSymbol = Symbol('mongoose#Model#db');
@@ -3687,6 +3688,19 @@ Model.castObject = function castObject(obj, options) {
36873688
}
36883689

36893690
if (schemaType.$isMongooseDocumentArray) {
3691+
const castNonArraysOption = schemaType.options?.castNonArrays ??schemaType.constructor.options.castNonArrays;
3692+
if (!Array.isArray(val)) {
3693+
if (!castNonArraysOption) {
3694+
if (!options.ignoreCastErrors) {
3695+
error = error || new ValidationError();
3696+
error.addError(path, new ObjectExpectedError(path, val));
3697+
}
3698+
} else {
3699+
cur[pieces[pieces.length - 1]] = [
3700+
Model.castObject.call(schemaType.caster, val)
3701+
];
3702+
}
3703+
}
36903704
continue;
36913705
}
36923706
if (schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) {

test/model.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7777,6 +7777,24 @@ describe('Model', function() {
77777777
TestModel.castObject(square).shape[0],
77787778
{ kind: 'Square', propertyPaths: [{ property: '42' }] }
77797779
);
7780+
7781+
const square2 = { shape: [{ kind: 'Square', propertyPaths: {} }] };
7782+
assert.deepStrictEqual(
7783+
TestModel.castObject(square2).shape[0],
7784+
{ kind: 'Square', propertyPaths: [{}] }
7785+
);
7786+
});
7787+
it('handles castNonArrays when document array is set to non-array value (gh-15075)', function() {
7788+
const sampleSchema = new mongoose.Schema({
7789+
sampleArray: {
7790+
type: [new mongoose.Schema({ name: String })],
7791+
castNonArrays: false
7792+
}
7793+
});
7794+
const Test = db.model('Test', sampleSchema);
7795+
7796+
const obj = { sampleArray: { name: 'Taco' } };
7797+
assert.throws(() => Test.castObject(obj), /Tried to set nested object field `sampleArray` to primitive value/);
77807798
});
77817799
});
77827800

0 commit comments

Comments
 (0)