@@ -281,8 +281,8 @@ export abstract class AbstractCursor<
281281 }
282282
283283 /** Returns current buffered documents */
284- readBufferedDocuments ( number ?: number ) : TSchema [ ] {
285- const bufferedDocs : TSchema [ ] = [ ] ;
284+ readBufferedDocuments ( number ?: number ) : NonNullable < TSchema > [ ] {
285+ const bufferedDocs : NonNullable < TSchema > [ ] = [ ] ;
286286 const documentsToRead = Math . min (
287287 number ?? this . documents ?. length ?? 0 ,
288288 this . documents ?. length ?? 0
@@ -457,29 +457,33 @@ export abstract class AbstractCursor<
457457 * results when this cursor had been previously accessed. In that case,
458458 * cursor.rewind() can be used to reset the cursor.
459459 */
460- async toArray ( ) : Promise < TSchema [ ] > {
460+ async toArray ( transform_temp ?: ( doc : TSchema ) => any ) : Promise < TSchema [ ] > {
461461 const array : TSchema [ ] = [ ] ;
462462
463- // when each loop iteration ends,documents will be empty and a 'await (const document of this)' will run a getMore operation
463+ this . transform = transform_temp ;
464+ // at the end of the loop (since readBufferedDocuments is called) the buffer will be empty
465+ // then, the 'await of' syntax will run a getMore call
464466 for await ( const document of this ) {
465467 array . push ( document ) ;
466- let docs = this . readBufferedDocuments ( ) ;
468+ const docs = this . readBufferedDocuments ( ) ;
467469 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- ) ;
470+ for ( const doc of docs ) {
471+ array . push ( await this . transformDocument ( doc ) ) ;
472+ }
473+ } else {
474+ array . push ( ...docs ) ;
477475 }
478- array . push ( ...docs ) ;
479476 }
480477 return array ;
481478 }
482479
480+ async toArrayOld ( ) : Promise < TSchema [ ] > {
481+ const array = [ ] ;
482+ for await ( const document of this ) {
483+ array . push ( document ) ;
484+ }
485+ return array ;
486+ }
483487 /**
484488 * Add a cursor flag to the cursor
485489 *
@@ -820,7 +824,7 @@ export abstract class AbstractCursor<
820824 }
821825
822826 /** @internal */
823- private async transformDocument ( document : NonNullable < TSchema > ) : Promise < TSchema > {
827+ private async transformDocument ( document : NonNullable < TSchema > ) : Promise < NonNullable < TSchema > > {
824828 if ( this . transform == null ) return document ;
825829
826830 try {
0 commit comments