File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -69,6 +69,7 @@ const util = require('util');
6969const utils = require ( './utils' ) ;
7070const minimize = require ( './helpers/minimize' ) ;
7171const MongooseBulkSaveIncompleteError = require ( './error/bulkSaveIncompleteError' ) ;
72+ const ObjectExpectedError = require ( './error/objectExpected' ) ;
7273
7374const modelCollectionSymbol = Symbol ( 'mongoose#Model#collection' ) ;
7475const 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 ) {
Original file line number Diff line number Diff 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 ) , / T r i e d t o s e t n e s t e d o b j e c t f i e l d ` s a m p l e A r r a y ` t o p r i m i t i v e v a l u e / ) ;
77807798 } ) ;
77817799 } ) ;
77827800
You can’t perform that action at this time.
0 commit comments