Skip to content

Commit

Permalink
Merge pull request #15124 from Automattic/vkarpov15/gh-15075-2
Browse files Browse the repository at this point in the history
fix(model): handle document array paths set to non-array values in Model.castObject()
  • Loading branch information
vkarpov15 authored Dec 22, 2024
2 parents bbca321 + dfd96dc commit 682160f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const util = require('util');
const utils = require('./utils');
const minimize = require('./helpers/minimize');
const MongooseBulkSaveIncompleteError = require('./error/bulkSaveIncompleteError');
const ObjectExpectedError = require('./error/objectExpected');

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

if (schemaType.$isMongooseDocumentArray) {
const castNonArraysOption = schemaType.options?.castNonArrays ??schemaType.constructor.options.castNonArrays;

Check failure on line 3691 in lib/model.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Operator '??' must be spaced
if (!Array.isArray(val)) {
if (!castNonArraysOption) {
if (!options.ignoreCastErrors) {
error = error || new ValidationError();
error.addError(path, new ObjectExpectedError(path, val));
}
} else {
cur[pieces[pieces.length - 1]] = [
Model.castObject.call(schemaType.caster, val)
];
}
}
continue;
}
if (schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) {
Expand Down
18 changes: 18 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7777,6 +7777,24 @@ describe('Model', function() {
TestModel.castObject(square).shape[0],
{ kind: 'Square', propertyPaths: [{ property: '42' }] }
);

const square2 = { shape: [{ kind: 'Square', propertyPaths: {} }] };
assert.deepStrictEqual(
TestModel.castObject(square2).shape[0],
{ kind: 'Square', propertyPaths: [{}] }
);
});
it('handles castNonArrays when document array is set to non-array value (gh-15075)', function() {
const sampleSchema = new mongoose.Schema({
sampleArray: {
type: [new mongoose.Schema({ name: String })],
castNonArrays: false
}
});
const Test = db.model('Test', sampleSchema);

const obj = { sampleArray: { name: 'Taco' } };
assert.throws(() => Test.castObject(obj), /Tried to set nested object field `sampleArray` to primitive value/);
});
});

Expand Down

0 comments on commit 682160f

Please sign in to comment.