Skip to content

Commit ef04d00

Browse files
committed
fix(cursor): hasNext consumes documents on cursor with limit
A recent change to allow use of `hasNext` with a cursor that is piped as a stream introduced a regression when a cursor with a limit is iterated. NODE-2483
1 parent b72fefe commit ef04d00

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/cursor.js

+6
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,13 @@ class Cursor extends CoreCursor {
210210
}
211211

212212
cursor.s.state = CursorState.OPEN;
213+
214+
// NODE-2482: merge this into the core cursor implementation
213215
cursor.cursorState.cursorIndex--;
216+
if (cursor.cursorState.limit > 0) {
217+
cursor.cursorState.currentLimit--;
218+
}
219+
214220
cb(null, true);
215221
});
216222
});

test/functional/cursor.test.js

+40
Original file line numberDiff line numberDiff line change
@@ -4569,4 +4569,44 @@ describe('Cursor', function() {
45694569
});
45704570
});
45714571
});
4572+
4573+
it('should correctly iterate all documents with a limit set', function(done) {
4574+
const configuration = this.configuration;
4575+
const client = configuration.newClient();
4576+
4577+
client.connect(err => {
4578+
expect(err).to.not.exist;
4579+
this.defer(() => client.close());
4580+
4581+
const collection = client.db().collection('documents');
4582+
collection.drop(() => {
4583+
const docs = [{ a: 1 }, { a: 2 }, { a: 3 }];
4584+
collection.insertMany(docs, err => {
4585+
expect(err).to.not.exist;
4586+
4587+
let cursor = collection.find({}).limit(5);
4588+
4589+
let bag = [];
4590+
function iterate() {
4591+
if (bag.length === docs.length) {
4592+
expect(bag).to.eql(docs);
4593+
return done();
4594+
}
4595+
4596+
cursor.hasNext((err, hasNext) => {
4597+
expect(err).to.not.exist;
4598+
expect(hasNext).to.be.true;
4599+
cursor.next((err, doc) => {
4600+
expect(err).to.not.exist;
4601+
bag.push(doc);
4602+
iterate();
4603+
});
4604+
});
4605+
}
4606+
4607+
iterate();
4608+
});
4609+
});
4610+
});
4611+
});
45724612
});

0 commit comments

Comments
 (0)