Skip to content

Commit 33b0efe

Browse files
committed
Modified limitRequest to allow negative limits to pass through to Mongo. Appropriate tests added.
1 parent bfe0e26 commit 33b0efe

File tree

2 files changed

+66
-5
lines changed

2 files changed

+66
-5
lines changed

lib/mongodb/cursor.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -316,11 +316,12 @@ Cursor.prototype.batchSize = function(batchSize, callback) {
316316
*/
317317
var limitRequest = function(self) {
318318
var requestedLimit = self.limitValue;
319-
320-
if(self.limitValue > 0) {
321-
if (self.batchSizeValue > 0) {
322-
requestedLimit = self.limitValue < self.batchSizeValue ?
323-
self.limitValue : self.batchSizeValue;
319+
var absLimitValue = Math.abs(self.limitValue);
320+
var absBatchValue = Math.abs(self.batchSizeValue);
321+
322+
if(absLimitValue > 0) {
323+
if (absBatchValue > 0) {
324+
requestedLimit = Math.min(absLimitValue, absBatchValue);
324325
}
325326
} else {
326327
requestedLimit = self.batchSizeValue;

test/cursor_test.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,66 @@ exports.shouldCorrectlyHandleLimitOnCursor = function(test) {
439439
});
440440
}
441441

442+
/**
443+
* @ignore
444+
* @api private
445+
*/
446+
exports.shouldCorrectlyHandleNegativeOneLimitOnCursor = function(test) {
447+
client.createCollection('test_cursor_negative_one_limit', function(err, collection) {
448+
Step(
449+
function insert() {
450+
var group = this.group();
451+
452+
for(var i = 0; i < 10; i++) {
453+
collection.save({'x':1}, {safe:true}, group());
454+
}
455+
},
456+
457+
function finished() {
458+
collection.find(function(err, cursor) {
459+
cursor.limit(-1, function(err, cursor) {
460+
cursor.toArray(function(err, items) {
461+
test.equal(1, items.length);
462+
// Let's close the db
463+
test.done();
464+
});
465+
});
466+
});
467+
}
468+
);
469+
});
470+
}
471+
472+
/**
473+
* @ignore
474+
* @api private
475+
*/
476+
exports.shouldCorrectlyHandleAnyNegativeLimitOnCursor = function(test) {
477+
client.createCollection('test_cursor_any_negative_limit', function(err, collection) {
478+
Step(
479+
function insert() {
480+
var group = this.group();
481+
482+
for(var i = 0; i < 10; i++) {
483+
collection.save({'x':1}, {safe:true}, group());
484+
}
485+
},
486+
487+
function finished() {
488+
collection.find(function(err, cursor) {
489+
cursor.limit(-5, function(err, cursor) {
490+
cursor.toArray(function(err, items) {
491+
test.equal(5, items.length);
492+
// Let's close the db
493+
test.done();
494+
});
495+
});
496+
});
497+
}
498+
);
499+
});
500+
}
501+
442502
/**
443503
* @ignore
444504
* @api private

0 commit comments

Comments
 (0)