diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index c43e5093..4d98e05e 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -347,13 +347,19 @@ Memory.prototype.all = function all(model, filter, callback) { }); function sorting(a, b) { + var undefinedA, undefinedB; + for (var i = 0, l = this.length; i < l; i++) { - if (a[this[i].key] > b[this[i].key]) { + undefinedB = b[this[i].key] === undefined && a[this[i].key] !== undefined; + undefinedA = a[this[i].key] === undefined && b[this[i].key] !== undefined; + + if (undefinedB || a[this[i].key] > b[this[i].key]) { return 1 * this[i].reverse; - } else if (a[this[i].key] < b[this[i].key]) { + } else if (undefinedA || a[this[i].key] < b[this[i].key]) { return -1 * this[i].reverse; } } + return 0; } }; diff --git a/test/memory.test.js b/test/memory.test.js index f07ab015..f3f16fd0 100644 --- a/test/memory.test.js +++ b/test/memory.test.js @@ -183,7 +183,7 @@ describe('Memory connector', function () { }); }); - it('support order with multiple fields', function (done) { + it('should support order with multiple fields', function (done) { User.find({order: 'vip ASC, seq DESC'}, function (err, posts) { should.not.exist(err); posts[0].seq.should.be.eql(4); @@ -192,6 +192,17 @@ describe('Memory connector', function () { }); }); + it('should sort undefined values to the end when ordered DESC', function (done) { + User.find({order: 'vip ASC, order DESC'}, function (err, posts) { + console.log(posts); + should.not.exist(err); + + posts[4].seq.should.be.eql(1); + posts[5].seq.should.be.eql(0); + done(); + }); + }); + it('should throw if order has wrong direction', function (done) { User.find({order: 'seq ABC'}, function (err, posts) { should.exist(err); @@ -200,11 +211,11 @@ describe('Memory connector', function () { }); it('should support neq operator for number', function (done) { - User.find({where: {order: {neq: 6}}}, function (err, users) { + User.find({where: {seq: {neq: 4}}}, function (err, users) { should.not.exist(err); users.length.should.be.equal(5); for (var i = 0; i < users.length; i++) { - users[i].order.should.not.be.equal(6); + users[i].seq.should.not.be.equal(4); } done(); }); @@ -242,7 +253,6 @@ describe('Memory connector', function () { email: 'john@b3atl3s.co.uk', role: 'lead', birthday: new Date('1980-12-08'), - order: 2, vip: true }, {