Skip to content

Commit 5db83ec

Browse files
authored
Merge pull request #14745 from Automattic/vkarpov15/getdrivercursor
feat(QueryCursor): add getDriverCursor() function that returns the raw driver cursor
2 parents f5a0af1 + 22b41df commit 5db83ec

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/cursor/queryCursor.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const eachAsync = require('../helpers/cursor/eachAsync');
1010
const helpers = require('../queryHelpers');
1111
const kareem = require('kareem');
1212
const immediate = require('../helpers/immediate');
13+
const { once } = require('node:events');
1314
const util = require('util');
1415

1516
/**
@@ -135,6 +136,25 @@ QueryCursor.prototype._read = function() {
135136
});
136137
};
137138

139+
/**
140+
* Returns the underlying cursor from the MongoDB Node driver that this cursor uses.
141+
*
142+
* @method getDriverCursor
143+
* @memberOf QueryCursor
144+
* @returns {Cursor} MongoDB Node driver cursor instance
145+
* @instance
146+
* @api public
147+
*/
148+
149+
QueryCursor.prototype.getDriverCursor = async function getDriverCursor() {
150+
if (this.cursor) {
151+
return this.cursor;
152+
}
153+
154+
await once(this, 'cursor');
155+
return this.cursor;
156+
};
157+
138158
/**
139159
* Registers a transform function which subsequently maps documents retrieved
140160
* via the streams interface or `.next()`

test/query.cursor.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -900,6 +900,25 @@ describe('QueryCursor', function() {
900900
assert.ok(err);
901901
assert.ok(err.message.includes('skipMiddlewareFunction'), err.message);
902902
});
903+
904+
it('returns the underlying Node driver cursor with getDriverCursor()', async function() {
905+
const schema = new mongoose.Schema({ name: String });
906+
907+
const Movie = db.model('Movie', schema);
908+
909+
await Movie.deleteMany({});
910+
await Movie.create([
911+
{ name: 'Kickboxer' },
912+
{ name: 'Ip Man' },
913+
{ name: 'Enter the Dragon' }
914+
]);
915+
916+
const cursor = await Movie.find({}).cursor();
917+
assert.ok(!cursor.cursor);
918+
const driverCursor = await cursor.getDriverCursor();
919+
assert.ok(cursor.cursor);
920+
assert.equal(driverCursor, cursor.cursor);
921+
});
903922
});
904923

905924
async function delay(ms) {

0 commit comments

Comments
 (0)