File tree Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Original file line number Diff line number Diff line change @@ -3831,16 +3831,14 @@ Document.prototype.$toObject = function(options, json) {
38313831 // need the original options the user passed in, plus `_isNested` and
38323832 // `_parentOptions` for checking whether we need to depopulate.
38333833 const cloneOptions = {
3834+ ...options ,
38343835 _isNested : true ,
38353836 json : json ,
38363837 minimize : _minimize ,
38373838 flattenMaps : flattenMaps ,
38383839 flattenObjectIds : flattenObjectIds ,
38393840 _seen : ( options && options . _seen ) || new Map ( ) ,
3840- _calledWithOptions : options . _calledWithOptions ,
3841- virtuals : options . virtuals ,
3842- getters : options . getters ,
3843- depopulate : options . depopulate
3841+ _calledWithOptions : options . _calledWithOptions
38443842 } ;
38453843
38463844 const depopulate = options . depopulate ||
Original file line number Diff line number Diff line change @@ -520,6 +520,34 @@ describe('document', function() {
520520 docs . toObject ( { transform : true } ) ;
521521 } ) ;
522522
523+ it ( 'propagates toObject transform function to all subdocuments (gh-14589)' , async function ( ) {
524+ const schema = new mongoose . Schema ( {
525+ name : String ,
526+ docArr : [ { name : String } ] ,
527+ subdoc : new mongoose . Schema ( { name : String } )
528+ } ) ;
529+ const TestModel = db . model ( 'Test' , schema ) ;
530+
531+ const doc = new TestModel ( {
532+ name : 'test' ,
533+ docArr : [ { name : 'test' } ] ,
534+ subdoc : { name : 'test' }
535+ } ) ;
536+
537+ // pass the transform as an inline option. Deletes `_id` property
538+ // from both the top-level document and the subdocument.
539+ const obj = doc . toObject ( { transform : deleteId } ) ;
540+
541+ assert . equal ( obj . _id , undefined ) ;
542+ assert . equal ( obj . subdoc . _id , undefined ) ;
543+ assert . equal ( obj . docArr [ 0 ] . _id , undefined ) ;
544+
545+ function deleteId ( doc , ret ) {
546+ delete ret . _id ;
547+ return ret ;
548+ }
549+ } ) ;
550+
523551 it ( 'disabling aliases in toObject options (gh-7548)' , function ( ) {
524552 const schema = new mongoose . Schema ( {
525553 name : {
You can’t perform that action at this time.
0 commit comments