Skip to content

fix(NODE-6367): enable mixed use of iteration APIs #4231

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Sep 12, 2024
2 changes: 1 addition & 1 deletion src/cursor/abstract_cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ export abstract class AbstractCursor<
}

async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
if (this.isClosed) {
if (this.closed) {
return;
}

Expand Down
89 changes: 89 additions & 0 deletions test/integration/crud/find_cursor_methods.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,4 +361,93 @@ describe('Find Cursor', function () {
}
});
});

describe('next + Symbol.asyncIterator()', function () {
let client;
let collection;
let cursor;

beforeEach(async function () {
client = this.configuration.newClient();
await client.connect();
collection = client.db('next-symbolasynciterator').collection('bar');
await collection.deleteMany({}, { writeConcern: { w: 'majority' } });
await collection.insertMany([{ a: 1 }, { a: 2 }], { writeConcern: { w: 'majority' } });
});

afterEach(async function () {
await cursor.close();
await client.close();
});

context('when all documents are retrieved in the first batch', function () {
it('allows combining iteration modes', async function () {
let count = 0;
cursor = collection.find().map(doc => {
count++;
return doc;
});

await cursor.next();
// eslint-disable-next-line no-unused-vars
for await (const _ of cursor) {
/* empty */
}

expect(count).to.equal(2);
});

it('works with next + next() loop', async function () {
let count = 0;
cursor = collection.find().map(doc => {
count++;
return doc;
});

await cursor.next();

let doc;
while ((doc = (await cursor.next()) && doc != null)) {
/** empty */
}

expect(count).to.equal(2);
});
});

context('when there are documents are not retrieved in the first batch', function () {
it('allows combining iteration modes', async function () {
let count = 0;
cursor = collection.find({}, { batchSize: 1 }).map(doc => {
count++;
return doc;
});

await cursor.next();
// eslint-disable-next-line no-unused-vars
for await (const _ of cursor) {
/* empty */
}

expect(count).to.equal(2);
});

it('works with next + next() loop', async function () {
let count = 0;
cursor = collection.find({}, { batchSize: 1 }).map(doc => {
count++;
return doc;
});

await cursor.next();

let doc;
while ((doc = (await cursor.next()) && doc != null)) {
/** empty */
}

expect(count).to.equal(2);
});
});
});
});