-
Type:
Bug
-
Resolution: Unresolved
-
Priority:
Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
PR: https://github.com/mongodb/node-mongodb-native/pull/4488
MongoDB Driver: documents?.clear() is not a function error in AbstractCursor.rewind()
Issue Description
When using the MongoDB Node.js driver, there's an issue in the rewind() method of AbstractCursor. The method attempts to call this.documents?.clear() without checking if the clear() method exists on the documents object.
In certain scenarios, particularly when the MongoDB driver uses an optimization called emptyGetMore to avoid unnecessary server calls, this.documents is set to a simplified object literal that lacks the clear() method:
CursorResponse.emptyGetMore =
;
This causes an error when rewind() is called on cursors that have this optimization applied:
rewind() {if (!this.initialized)
h2. Impact
This issue can cause applications to crash when:
# Using cursor operations that internally call rewind()
# Working with cursors that have been optimized using emptyGetMore
# Attempting to reset or reuse cursors after they've been exhausted
h2. Reproduction Details
In this repository, the reproduction.js script demonstrates this issue by:
# Creating a MongoDB cursor with a small batch size
# Consuming all documents to exhaust the cursor
# Simulating the emptyGetMore optimization by replacing the documents object with one that lacks a clear() method
# Attempting to rewind the cursor, which triggers the error
# Trying to reuse the cursor, which would normally work if rewind() succeeded
h3. Running the Reproduction
# Install dependenciesnpm i# Run the reproduction scriptnode reproduction.js
Expected output will show the error:
{{Rewind error: this.documents?.clear is not a function
Error name: TypeError}}
h2. Proposed Solution
The issue can be fixed by modifying the rewind() method to safely handle cases where documents doesn't have a clear() method. Here's the proposed fix:
rewind() {if (!this.initialized) {return;}
this.cursorId = null;// Check if documents exists and has a clear method before calling itif (this.documents && typeof this.documents.clear === 'function')
{this.documents.clear();}else
{// If documents is the emptyGetMore object or doesn't have the clear() method// Simply set it to null to force reinitializationthis.documents = null;}this.isClosed = false;this.isKilled = false;this.initialized = false;// ... rest of the method}
Why This Solution Works
- Safety: The solution checks if clear() exists before calling it
- Functionality: Setting documents to null achieves the same goal as clear() - it resets the cursor's document buffer
- Compatibility: The solution maintains compatibility with both regular cursors and optimized emptyGetMore cursors
- Performance: The solution doesn't introduce any significant overhead
References
- is duplicated by
-
NODE-6877 node-mongodb-native - PR #4488: fix(cursor): ensure documents are cleared correctly to handle emptyGe…
-
- Closed
-