@@ -16,7 +16,7 @@ import { FindOperation, type FindOptions } from '../operations/find';
1616import type { Hint } from '../operations/operation' ;
1717import type { ClientSession } from '../sessions' ;
1818import { formatSort , type Sort , type SortDirection } from '../sort' ;
19- import { emitWarningOnce , mergeOptions , type MongoDBNamespace , squashError } from '../utils' ;
19+ import { emitWarningOnce , mergeOptions , type MongoDBNamespace , noop , squashError } from '../utils' ;
2020import { type InitialCursorResponse } from './abstract_cursor' ;
2121import { ExplainableCursor } from './explainable_cursor' ;
2222
@@ -100,9 +100,10 @@ export class FindCursor<TSchema = any> extends ExplainableCursor<TSchema> {
100100 /** @internal */
101101 override async getMore ( ) : Promise < CursorResponse > {
102102 const numReturned = this . numReturned ;
103- const limit = this . findOptions . limit ;
103+ const limit = this . findOptions . limit ?? Infinity ;
104+ const remaining = limit - numReturned ;
104105
105- if ( numReturned && limit && numReturned >= limit ) {
106+ if ( numReturned >= limit ) {
106107 try {
107108 await this . close ( ) ;
108109 } catch ( error ) {
@@ -119,11 +120,28 @@ export class FindCursor<TSchema = any> extends ExplainableCursor<TSchema> {
119120 return CursorResponse . emptyGetMore ;
120121 }
121122
122- const response = await super . getMore ( ) ;
123+ // TODO(DRIVERS-1448): Remove logic to enforce `limit` in the driver
124+ let cleanup : ( ) => void = noop ;
125+ const { batchSize } = this . cursorOptions ;
126+ if ( batchSize != null && batchSize > remaining ) {
127+ this . cursorOptions . batchSize = remaining ;
128+
129+ // After executing the final getMore, re-assign the batchSize back to its original value so that
130+ // if the cursor is rewound and executed, the batchSize is still correct.
131+ cleanup = ( ) => {
132+ this . cursorOptions . batchSize = batchSize ;
133+ } ;
134+ }
135+
136+ try {
137+ const response = await super . getMore ( ) ;
123138
124- this . numReturned = this . numReturned + response . batchSize ;
139+ this . numReturned = this . numReturned + response . batchSize ;
125140
126- return response ;
141+ return response ;
142+ } finally {
143+ cleanup ?.( ) ;
144+ }
127145 }
128146
129147 /**
0 commit comments