From 994387e941d3774ee6465e344243d8476d4677cb Mon Sep 17 00:00:00 2001 From: Noah Passalacqua Date: Sun, 20 Nov 2022 18:10:59 +0000 Subject: [PATCH 1/2] add `rewind` function to `QueryCursor` Wraps the `mongodb.FindCursor.rewind` function to reset the cursor to its uninitialized state, effectively resetting the cursor to the beginning. --- lib/cursor/QueryCursor.js | 15 +++++++++++++++ types/cursor.d.ts | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/lib/cursor/QueryCursor.js b/lib/cursor/QueryCursor.js index 3a2e683890e..a73224d2240 100644 --- a/lib/cursor/QueryCursor.js +++ b/lib/cursor/QueryCursor.js @@ -194,6 +194,21 @@ QueryCursor.prototype.close = function(callback) { }, this.model.events); }; +/** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + * + * @return {AggregationCursor} this + * @api public + * @method rewind + */ + + QueryCursor.prototype.rewind = function() { + this.cursor.rewind(); + return this; +}; + /** * Get the next document from this cursor. Will return `null` when there are * no documents left. diff --git a/types/cursor.d.ts b/types/cursor.d.ts index 80e43530dff..bd514542676 100644 --- a/types/cursor.d.ts +++ b/types/cursor.d.ts @@ -26,6 +26,13 @@ declare module 'mongoose' { close(callback: CallbackWithoutResult): void; close(): Promise; + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): this; + /** * Execute `fn` for every document(s) in the cursor. If batchSize is provided * `fn` will be executed for each batch of documents. If `fn` returns a promise, From 934bb87c4dfec857c3997591ba2ca75fe3b765ae Mon Sep 17 00:00:00 2001 From: Noah Passalacqua Date: Mon, 21 Nov 2022 00:14:30 -0600 Subject: [PATCH 2/2] wrap function --- lib/cursor/QueryCursor.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/cursor/QueryCursor.js b/lib/cursor/QueryCursor.js index a73224d2240..f862d0f4fde 100644 --- a/lib/cursor/QueryCursor.js +++ b/lib/cursor/QueryCursor.js @@ -204,8 +204,11 @@ QueryCursor.prototype.close = function(callback) { * @method rewind */ - QueryCursor.prototype.rewind = function() { - this.cursor.rewind(); +QueryCursor.prototype.rewind = function() { + const _this = this; + _waitForCursor(this, function() { + _this.cursor.rewind(); + }); return this; };