Skip to content

Commit 70ef3f5

Browse files
feat(NODE-5906): optimize toArray to batches
1 parent d85f827 commit 70ef3f5

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/cursor/abstract_cursor.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ export abstract class AbstractCursor<
297297

298298
return bufferedDocs;
299299
}
300+
300301
async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
301302
if (this.isClosed) {
302303
return;
@@ -457,9 +458,24 @@ export abstract class AbstractCursor<
457458
* cursor.rewind() can be used to reset the cursor.
458459
*/
459460
async toArray(): Promise<TSchema[]> {
460-
const array = [];
461+
const array: TSchema[] = [];
462+
463+
// when each loop iteration ends,documents will be empty and a 'await (const document of this)' will run a getMore operation
461464
for await (const document of this) {
462465
array.push(document);
466+
let docs = this.readBufferedDocuments();
467+
if (this.transform != null) {
468+
docs = await Promise.all(
469+
docs.map(async doc => {
470+
if (doc != null) {
471+
return await this.transformDocument(doc);
472+
} else {
473+
throw Error;
474+
}
475+
})
476+
);
477+
}
478+
array.push(...docs);
463479
}
464480
return array;
465481
}

0 commit comments

Comments
 (0)