@@ -2836,6 +2836,13 @@ Document.prototype.$toObject = function(options, json) {
2836
2836
minimize : _minimize
2837
2837
} ) ;
2838
2838
2839
+ if ( utils . hasUserDefinedProperty ( options , 'getters' ) ) {
2840
+ cloneOptions . getters = options . getters ;
2841
+ }
2842
+ if ( utils . hasUserDefinedProperty ( options , 'virtuals' ) ) {
2843
+ cloneOptions . virtuals = options . virtuals ;
2844
+ }
2845
+
2839
2846
const depopulate = options . depopulate ||
2840
2847
get ( options , '_parentOptions.depopulate' , false ) ;
2841
2848
// _isNested will only be true if this is not the top level document, we
@@ -2852,6 +2859,10 @@ Document.prototype.$toObject = function(options, json) {
2852
2859
options . minimize = _minimize ;
2853
2860
2854
2861
cloneOptions . _parentOptions = options ;
2862
+ cloneOptions . _skipSingleNestedGetters = true ;
2863
+
2864
+ const gettersOptions = Object . assign ( { } , cloneOptions ) ;
2865
+ gettersOptions . _skipSingleNestedGetters = false ;
2855
2866
2856
2867
// remember the root transform function
2857
2868
// to save it from being overwritten by sub-transform functions
@@ -2860,16 +2871,15 @@ Document.prototype.$toObject = function(options, json) {
2860
2871
let ret = clone ( this . _doc , cloneOptions ) || { } ;
2861
2872
2862
2873
if ( options . getters ) {
2863
- applyGetters ( this , ret , cloneOptions ) ;
2864
- // applyGetters for paths will add nested empty objects;
2865
- // if minimize is set, we need to remove them.
2874
+ applyGetters ( this , ret , gettersOptions ) ;
2875
+
2866
2876
if ( options . minimize ) {
2867
2877
ret = minimize ( ret ) || { } ;
2868
2878
}
2869
2879
}
2870
2880
2871
- if ( options . virtuals || options . getters && options . virtuals !== false ) {
2872
- applyVirtuals ( this , ret , cloneOptions , options ) ;
2881
+ if ( options . virtuals || ( options . getters && options . virtuals !== false ) ) {
2882
+ applyVirtuals ( this , ret , gettersOptions , options ) ;
2873
2883
}
2874
2884
2875
2885
if ( options . versionKey === false && this . schema . options . versionKey ) {
@@ -3180,12 +3190,7 @@ function applyGetters(self, json, options) {
3180
3190
v = cur [ part ] ;
3181
3191
if ( ii === last ) {
3182
3192
const val = self . get ( path ) ;
3183
- // Ignore single nested docs: getters will run because of `clone()`
3184
- // before `applyGetters()` in `$toObject()`. Quirk because single
3185
- // nested subdocs are hydrated docs in `_doc` as opposed to POJOs.
3186
- if ( val != null && val . $__ == null ) {
3187
- branch [ part ] = clone ( val , options ) ;
3188
- }
3193
+ branch [ part ] = clone ( val , options ) ;
3189
3194
} else if ( v == null ) {
3190
3195
if ( part in cur ) {
3191
3196
branch [ part ] = v ;
0 commit comments