diff --git a/lib/dao.js b/lib/dao.js index 00fbf18c..f2e55a26 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -351,19 +351,29 @@ DataAccessObject.sortByIds = function(ids, results) { return (typeof id === 'object') ? id.toString() : id; }); - results.sort(function(x, y) { - var idA = (typeof x[pk] === 'object') ? x[pk].toString() : x[pk]; - var idB = (typeof y[pk] === 'object') ? y[pk].toString() : y[pk]; - var a = ids.indexOf(idA); - var b = ids.indexOf(idB); - if (a === -1 || b === -1) return 1; // last - if (a !== b) { - if (a > b) return 1; - if (a < b) return -1; - } + var indexOf = function(x) { + var id = (typeof x[pk] === 'object') ? x[pk].toString() : x[pk]; + return ids.indexOf(id); + }; + + var heading = []; + var tailing = []; + + results.forEach(function(x) { + var idx = indexOf(x); + idx === -1 ? tailing.push(x) : heading.push(x); }); - return results; + heading.sort(function(x, y) { + var a = indexOf(x); + var b = indexOf(y); + if (a === -1 || b === -1) return 1; // last + if (a === b) return 0; + if (a > b) return 1; + if (a < b) return -1; + }); + + return heading.concat(tailing); }; function convertNullToNotFoundError(ctx, cb) { diff --git a/test/basic-querying.test.js b/test/basic-querying.test.js index dd26928a..d978fe88 100644 --- a/test/basic-querying.test.js +++ b/test/basic-querying.test.js @@ -87,6 +87,33 @@ describe('basic-querying', function () { done(); }); }); + + it('should sortByIds', function(done) { + User.find(function(err, users) { + sorted = User.sortByIds([6, 5, 4, 3, 2, 1], users); + var names = sorted.map(function(u) { return u.name; }); + names.should.eql(['f', 'e', 'd', 'c', 'b', 'a']); + done(); + }); + }); + + it('should sortByIds - partial ids (1)', function(done) { + User.find(function(err, users) { + sorted = User.sortByIds([6, 5, 4], users); + var names = sorted.map(function(u) { return u.name; }); + names.should.eql(['f', 'e', 'd', 'a', 'b', 'c']); + done(); + }); + }); + + it('should sortByIds - partial ids (2)', function(done) { + User.find(function(err, users) { + sorted = User.sortByIds([5, 3, 2], users); + var names = sorted.map(function(u) { return u.name; }); + names.should.eql(['e', 'c', 'b', 'a', 'd', 'f']); + done(); + }); + }); });