Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(model): handle document array paths set to non-array values in Model.castObject() #15124

Merged
merged 2 commits into from
Dec 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 != null ? schemaType.options.castNonArrays : schemaType.constructor.options.castNonArrays;
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
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
Loading