@@ -146,6 +146,8 @@ export abstract class AbstractCursor<
146
146
/** @internal */
147
147
private isClosed : boolean ;
148
148
/** @internal */
149
+ private isForceClosed : boolean ;
150
+ /** @internal */
149
151
private isKilled : boolean ;
150
152
/** @internal */
151
153
protected readonly cursorOptions : InternalAbstractCursorOptions ;
@@ -169,6 +171,7 @@ export abstract class AbstractCursor<
169
171
this . cursorId = null ;
170
172
this . initialized = false ;
171
173
this . isClosed = false ;
174
+ this . isForceClosed = false ;
172
175
this . isKilled = false ;
173
176
this . cursorOptions = {
174
177
readPreference :
@@ -369,7 +372,7 @@ export abstract class AbstractCursor<
369
372
}
370
373
371
374
async hasNext ( ) : Promise < boolean > {
372
- if ( this . cursorId === Long . ZERO ) {
375
+ if ( this . cursorId === Long . ZERO || this . isForceClosed ) {
373
376
return false ;
374
377
}
375
378
@@ -385,7 +388,7 @@ export abstract class AbstractCursor<
385
388
386
389
/** Get the next available document from the cursor, returns null if no more documents are available. */
387
390
async next ( ) : Promise < TSchema | null > {
388
- if ( this . cursorId === Long . ZERO ) {
391
+ if ( this . cursorId === Long . ZERO || this . isForceClosed ) {
389
392
throw new MongoCursorExhaustedError ( ) ;
390
393
}
391
394
@@ -405,7 +408,7 @@ export abstract class AbstractCursor<
405
408
* Try to get the next available document from the cursor or `null` if an empty batch is returned
406
409
*/
407
410
async tryNext ( ) : Promise < TSchema | null > {
408
- if ( this . cursorId === Long . ZERO ) {
411
+ if ( this . cursorId === Long . ZERO || this . isForceClosed ) {
409
412
throw new MongoCursorExhaustedError ( ) ;
410
413
}
411
414
@@ -447,6 +450,12 @@ export abstract class AbstractCursor<
447
450
}
448
451
449
452
async close ( ) : Promise < void > {
453
+ // We flag that an explicit call to close the cursor has happened, so no matter
454
+ // what the current state is it can no longer be used. This is do to areas in the
455
+ // cursor that are setting the isClosed flag or cursor id to zero without going
456
+ // through this path.
457
+ this . isForceClosed = true ;
458
+ this . documents ?. clear ( ) ;
450
459
await this . cleanup ( ) ;
451
460
}
452
461
0 commit comments