Skip to content

Commit ba84660

Browse files
fix pre-4.4 behavior
1 parent 6a08c88 commit ba84660

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/cursor/find_cursor.ts

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { FindOperation, type FindOptions } from '../operations/find';
1616
import type { Hint } from '../operations/operation';
1717
import type { ClientSession } from '../sessions';
1818
import { 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';
2020
import { type InitialCursorResponse } from './abstract_cursor';
2121
import { 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

Comments
 (0)