Limit and sort together tested

pull/2/head
Louis Chatriot 11 years ago
parent 6c674b7f82
commit 4b780652d4
  1. 17
      lib/cursor.js
  2. 44
      test/cursor.test.js

@ -17,7 +17,7 @@ function Cursor (db, query) {
/**
* Set a limit the number of results
* Set a limit to the number of results
*/
Cursor.prototype.limit = function(limit) {
this._limit = limit;
@ -25,6 +25,15 @@ Cursor.prototype.limit = function(limit) {
};
/**
* Skip a the number of results
*/
Cursor.prototype.skip = function(skip) {
this._skip = skip;
return this;
};
/**
* Sort results of the query
* @Param {SortQuery} sortQuery - SortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending
@ -67,6 +76,12 @@ Cursor.prototype.sort = function(sortQuery) {
return self._sort[key] * model.compareThings(model.getDotValue(a, key), model.getDotValue(b, key));
});
});
// Applying limit and skip
var limit = this._limit || res.length
, skip = this._skip || 0;
res = res.slice(skip, skip + limit);
}
return callback(null, res);

@ -154,8 +154,7 @@ describe.only('Cursor', function () {
});
it('Ability to chain sorting and exec', function (done) {
var i;
var i;
async.waterfall([
function (cb) {
d.insert({ age: 5 }, function (err) {
@ -195,6 +194,45 @@ describe.only('Cursor', function () {
], done);
});
it('Using limiting and sorting', function (done) {
var i;
async.waterfall([
function (cb) {
d.insert({ age: 5 }, function (err) {
d.insert({ age: 57 }, function (err) {
d.insert({ age: 52 }, function (err) {
d.insert({ age: 23 }, function (err) {
d.insert({ age: 89 }, function (err) {
return cb();
});
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(5);
docs[1].age.should.equal(23);
docs[2].age.should.equal(52);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).limit(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].age.should.equal(89);
docs[1].age.should.equal(57);
cb();
});
}
], done);
});
@ -203,3 +241,5 @@ describe.only('Cursor', function () {
}); // ===== End of 'Sorting' =====
});

Loading…
Cancel
Save