@@ -12538,6 +12538,38 @@ describe('document', function() {
12538
12538
assert . equal ( purchaseFromDbCart . products [ 0 ] . product . name , 'Bug' ) ;
12539
12539
assert . equal ( purchaseFromDbCart . singleProduct . name , 'Bug' ) ;
12540
12540
} ) ;
12541
+
12542
+ it ( 'handles virtuals that are stored as objects but getter returns string with toJSON (gh-14446)' , async function ( ) {
12543
+ const childSchema = new mongoose . Schema ( ) ;
12544
+
12545
+ childSchema . virtual ( 'name' )
12546
+ . set ( function ( values ) {
12547
+ for ( const [ lang , val ] of Object . entries ( values ) ) {
12548
+ this . set ( `name.${ lang } ` , val ) ;
12549
+ }
12550
+ } )
12551
+ . get ( function ( ) {
12552
+ return this . $__getValue ( `name.${ this . lang } ` ) ;
12553
+ } ) ;
12554
+
12555
+ childSchema . add ( { name : { en : { type : String } , de : { type : String } } } ) ;
12556
+
12557
+ const ChildModel = db . model ( 'Child' , childSchema ) ;
12558
+ const ParentModel = db . model ( 'Parent' , new mongoose . Schema ( {
12559
+ children : [ childSchema ]
12560
+ } ) ) ;
12561
+
12562
+ const child = await ChildModel . create ( { name : { en : 'Stephen' , de : 'Stefan' } } ) ;
12563
+ child . lang = 'en' ;
12564
+ assert . equal ( child . name , 'Stephen' ) ;
12565
+
12566
+ const parent = await ParentModel . create ( {
12567
+ children : [ { name : { en : 'Stephen' , de : 'Stefan' } } ]
12568
+ } ) ;
12569
+ parent . children [ 0 ] . lang = 'de' ;
12570
+ const obj = parent . toJSON ( { getters : true } ) ;
12571
+ assert . equal ( obj . children [ 0 ] . name , 'Stefan' ) ;
12572
+ } ) ;
12541
12573
} ) ;
12542
12574
12543
12575
describe ( 'Check if instance function that is supplied in schema option is availabe' , function ( ) {
0 commit comments