Skip to content

Commit

Permalink
fix(cursor): hasNext consumes documents on cursor with limit
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mbroadst committed Mar 5, 2020
1 parent b72fefe commit ef04d00
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/cursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,13 @@ class Cursor extends CoreCursor {
}

cursor.s.state = CursorState.OPEN;

// NODE-2482: merge this into the core cursor implementation
cursor.cursorState.cursorIndex--;
if (cursor.cursorState.limit > 0) {
cursor.cursorState.currentLimit--;
}

cb(null, true);
});
});
Expand Down
40 changes: 40 additions & 0 deletions test/functional/cursor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4569,4 +4569,44 @@ describe('Cursor', function() {
});
});
});

it('should correctly iterate all documents with a limit set', function(done) {
const configuration = this.configuration;
const client = configuration.newClient();

client.connect(err => {
expect(err).to.not.exist;
this.defer(() => client.close());

const collection = client.db().collection('documents');
collection.drop(() => {
const docs = [{ a: 1 }, { a: 2 }, { a: 3 }];
collection.insertMany(docs, err => {
expect(err).to.not.exist;

let cursor = collection.find({}).limit(5);

let bag = [];
function iterate() {
if (bag.length === docs.length) {
expect(bag).to.eql(docs);
return done();
}

cursor.hasNext((err, hasNext) => {
expect(err).to.not.exist;
expect(hasNext).to.be.true;
cursor.next((err, doc) => {
expect(err).to.not.exist;
bag.push(doc);
iterate();
});
});
}

iterate();
});
});
});
});
});

0 comments on commit ef04d00

Please sign in to comment.