@@ -118,7 +118,6 @@ class MongoosePlugin implements SwPlugin {
118118 arguments [ arguments . length - 1 ] = function ( ) {
119119 // in case of immediate synchronous callback from mongoose
120120 ( span as any ) . mongooseInCall = false ;
121-
122121 wrappedCallback . apply ( this , arguments as any ) ;
123122 } ;
124123 }
@@ -130,7 +129,42 @@ class MongoosePlugin implements SwPlugin {
130129 if ( ! hasCB ) {
131130 if ( ret && typeof ret . then === 'function' ) {
132131 // generic Promise check
133- ret = wrapPromise ( span , ret ) ;
132+
133+ if ( ret . constructor . name != 'Query' ) {
134+ ret = wrapPromise ( span , ret ) ;
135+ } else {
136+ // Mongoose Query object
137+ const chainMethods = [ 'select' , 'sort' , 'skip' , 'limit' , 'populate' ] ;
138+
139+ // Mongoose Query object
140+ const originalThen = ret . then ;
141+ const originalExec = ret . exec ;
142+ const originalLean = ret . lean ;
143+
144+ // Preserve the query chain methods using arrow functions to maintain context
145+ ret . then = ( ...args : any [ ] ) => wrapPromise ( span , originalThen . apply ( ret , args ) ) ;
146+ ret . exec = ( ...args : any [ ] ) => wrapPromise ( span , originalExec . apply ( ret , args ) ) ;
147+ ret . lean = ( ...args : any [ ] ) => {
148+ const leanQuery = originalLean . apply ( ret , args ) ;
149+ // Preserve other chain methods on the lean result
150+ leanQuery . then = ret . then ;
151+ leanQuery . exec = ret . exec ;
152+ return leanQuery ;
153+ } ;
154+ // Wrap other common query methods that might be chained
155+ chainMethods . forEach ( ( method ) => {
156+ if ( ret [ method ] ) {
157+ const originalMethod = ret [ method ] ;
158+ ret [ method ] = ( ...args : any [ ] ) => {
159+ const result = originalMethod . apply ( ret , args ) ;
160+ result . then = ret . then ;
161+ result . exec = ret . exec ;
162+ result . lean = ret . lean ;
163+ return result ;
164+ } ;
165+ }
166+ } ) ;
167+ }
134168 } else {
135169 // no callback passed in and no Promise or Cursor returned, play it safe
136170 span . stop ( ) ;
0 commit comments