@@ -313,23 +313,25 @@ export class Server extends TypedEventEmitter<ServerEvents> {
313
313
// Incrementing the operation count above the logic to handle load balanced mode would
314
314
// require special logic to decrement it again, or would double increment. Instead, we
315
315
// increment the count after this check.
316
- if ( this . loadBalanced && session && conn == null && isPinnableCommand ( cmd , session ) ) {
317
- conn = await this . pool . checkOut ( ) ;
318
- session . pin ( conn ) ;
319
- }
316
+
317
+ const connShouldBePinned =
318
+ this . loadBalanced && session != null && isPinnableCommand ( cmd , session ) ;
320
319
321
320
this . incrementOperationCount ( ) ;
322
321
if ( ! conn ) {
323
322
try {
324
323
conn = await this . pool . checkOut ( ) ;
325
324
} catch ( checkoutError ) {
326
325
if ( ! ( checkoutError instanceof PoolClearedError ) ) this . handleError ( checkoutError ) ;
327
-
328
326
this . decrementOperationCount ( ) ;
329
327
throw checkoutError ;
330
328
}
331
329
}
332
330
331
+ if ( connShouldBePinned && ! session . isPinned ) {
332
+ session . pin ( conn ) ;
333
+ }
334
+
333
335
// Reauth flow
334
336
try {
335
337
return await this . executeCommand ( conn , ns , cmd , finalOptions ) ;
@@ -344,8 +346,10 @@ export class Server extends TypedEventEmitter<ServerEvents> {
344
346
throw operationError ;
345
347
}
346
348
} finally {
347
- this . pool . checkIn ( conn ) ;
348
- this . decrementOperationCount ( ) ;
349
+ if ( ! connShouldBePinned ) {
350
+ this . pool . checkIn ( conn ) ;
351
+ this . decrementOperationCount ( ) ;
352
+ }
349
353
}
350
354
}
351
355
@@ -362,8 +366,8 @@ export class Server extends TypedEventEmitter<ServerEvents> {
362
366
) : Promise < Document > {
363
367
try {
364
368
return await conn . command ( ns , cmd , options ) ;
365
- } catch ( commandOptions ) {
366
- throw this . decorateAndHandleError ( conn , cmd , options , commandOptions ) ;
369
+ } catch ( commandError ) {
370
+ throw this . decorateAndHandleError ( conn , cmd , options , commandError ) ;
367
371
}
368
372
}
369
373
@@ -526,6 +530,7 @@ function isPinnableCommand(cmd: Document, session?: ClientSession): boolean {
526
530
if ( session ) {
527
531
return (
528
532
session . inTransaction ( ) ||
533
+ ( session . transaction . isCommitted && 'commitTransaction' in cmd ) ||
529
534
'aggregate' in cmd ||
530
535
'find' in cmd ||
531
536
'getMore' in cmd ||
0 commit comments