From 184b817e72f932bad5372ad4d05ae47b3673748a Mon Sep 17 00:00:00 2001 From: Rebecca Weinberger Date: Wed, 6 Jun 2018 17:34:05 -0400 Subject: [PATCH] fix(cursor): cursor hasNext returns false when exhausted Instead of throwing an error when the cursor is exhausted, the hasNext method returns false. Fixes NODE-1197 --- lib/cursor.js | 4 ++++ test/functional/cursor_tests.js | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/cursor.js b/lib/cursor.js index 040373d92a..d39d84a1fc 100644 --- a/lib/cursor.js +++ b/lib/cursor.js @@ -237,6 +237,10 @@ const hasNext = (self, callback) => { return callback(null, true); } + if (self.isNotified()) { + return callback(null, false); + } + nextObject(self, function(err, doc) { if (err) return callback(err, null); if (self.s.state === Cursor.CLOSED || self.isDead()) return callback(null, false); diff --git a/test/functional/cursor_tests.js b/test/functional/cursor_tests.js index 16d381e9b6..6baff9c244 100644 --- a/test/functional/cursor_tests.js +++ b/test/functional/cursor_tests.js @@ -4396,4 +4396,31 @@ describe('Cursor', function() { cursor.close(() => client.close(() => done())); }); }); + + it('should return false when exhausted and hasNext called more than once', function(done) { + const configuration = this.configuration; + const client = configuration.newClient({ w: 1 }, { poolSize: 1, auto_reconnect: false }); + + client.connect(function(err, client) { + const db = client.db(configuration.db); + + db.createCollection('cursor_hasNext_test').then(function() { + const cursor = db.collection('cursor_hasNext_test').find(); + + cursor + .hasNext() + .then(function(val1) { + expect(val1).to.equal(false); + return cursor.hasNext(); + }) + .then(function(val2) { + expect(val2).to.equal(false); + cursor.close(() => client.close(() => done())); + }) + .catch(err => { + cursor.close(() => client.close(() => done(err))); + }); + }); + }); + }); });