Skip to content

Commit ac8fafd

Browse files
committed
fix(queryCursor): add _transformForAsyncIterator transform after user-defined transforms
Fix mongoosejs/mongoose-lean-getters#44
1 parent 4c7bdaa commit ac8fafd

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

lib/cursor/queryCursor.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ function QueryCursor(query) {
7777
if (this.options.transform) {
7878
this._transforms.push(this.options.transform);
7979
}
80+
if (this._mongooseOptions._transformForAsyncIterator) {
81+
this._transforms.push(_transformForAsyncIterator);
82+
}
8083
// Re: gh-8039, you need to set the `cursor.batchSize` option, top-level
8184
// `batchSize` option doesn't work.
8285
if (this.options.batchSize) {
@@ -396,9 +399,7 @@ QueryCursor.prototype.transformNull = function(val) {
396399
*/
397400

398401
QueryCursor.prototype._transformForAsyncIterator = function() {
399-
if (this._transforms.indexOf(_transformForAsyncIterator) === -1) {
400-
this.map(_transformForAsyncIterator);
401-
}
402+
this._mongooseOptions._transformForAsyncIterator = true;
402403
return this;
403404
};
404405

test/query.test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2354,6 +2354,19 @@ describe('Query', function() {
23542354
assert.strictEqual(called, 1);
23552355
});
23562356

2357+
it('transform with for/await and cursor', async function() {
2358+
const Model = db.model('Test', new Schema({ name: String }));
2359+
2360+
await Model.create({ name: 'test' });
2361+
const cursor = Model.find().transform(doc => doc?.name.toUpperCase() ?? null).cursor();
2362+
const names = [];
2363+
for await (const name of cursor) {
2364+
names.push(name);
2365+
}
2366+
2367+
assert.deepStrictEqual(names, ['TEST']);
2368+
});
2369+
23572370
describe('orFail (gh-6841)', function() {
23582371
let Model;
23592372

0 commit comments

Comments
 (0)