Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

fix Query#sort support

disallows passing arrays: sort(['path', 'ascending']) // throws!
correct processes objects: sort({ path: 1 })          // works!
prevents unhelpful driver error msgs from being thrown

closes #671
  • Loading branch information...
commit 63554e9eac22b72e31c73b08fe1575d9ddfec388 1 parent d8d25e1
@aheckmann authored
Showing with 39 additions and 1 deletion.
  1. +27 −1 lib/query.js
  2. +12 −0 test/query.test.js
View
28 lib/query.js
@@ -801,21 +801,47 @@ Query.prototype._applyFields = function (fields) {
* query.sort('test', 1)
* query.sort('field', -1)
* query.sort('field', -1, 'test', 1)
+ * query.sort({ field: 'asc', test: -1 })
*
* @api public
*/
Query.prototype.sort = function () {
+ if (Array.isArray(arguments[0])) return typeErr(arguments[0]);
+
var sort = this.options.sort || (this.options.sort = []);
inGroupsOf(2, arguments, function (field, value) {
- sort.push([field, value]);
+ if (field && 'Object' == field.constructor.name) {
+ Object.keys(field).forEach(function (key) {
+ push(key, field[key]);
+ });
+ } else {
+ push(field, value);
+ }
});
+ function push (field, value) {
+ var val = String(value || 1).toLowerCase();
+ if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {
+ return typeErr(value);
+ }
+ sort.push([field, value]);
+ }
+
return this;
};
/**
+ * @ignore
+ */
+
+function typeErr (val) {
+ if (Array.isArray(val)) val = '['+val+']';
+ throw new TypeError('Invalid sort clause: ' + val);
+}
+
+/**
* asc
*
* Sorts ascending.
View
12 test/query.test.js
@@ -553,6 +553,18 @@ module.exports = {
var query = new Query();
query.sort('a', 1, 'c', -1, 'b', 1);
query.options.sort.should.eql([['a', 1], ['c', -1], ['b', 1]]);
+ query = new Query();
+ query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'});
+ query.options.sort.should.eql([['a', 1], ['c', -1], ['b', 'asc'], ['e', 'descending'], ['f', 'ascending']]);
+ query = new Query();
+ var e;
+ try {
+ query.sort(['a', 1]);
+ } catch (err) {
+ e= err;
+ }
+ should.exist(e, 'uh oh. no error was thrown');
+ e.message.should.eql('Invalid sort clause: [a,1]');
},
'test Query#asc and Query#desc': function () {
Please sign in to comment.
Something went wrong with that request. Please try again.