/
order.js
47 lines (41 loc) · 987 Bytes
/
order.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
module.exports = function(mongoose) {
'use strict';
mongoose.Query.prototype.order = function (options) {
if (!options || !options.sort) {
return this;
}
var
fields = [],
self = this,
sort = options.sort || {},
value = null;
if (typeof sort === 'string') {
fields = sort.split(/\,/g).map(function (field) { return field.trim(); });
} else if (Array.isArray(sort) && sort.length) {
fields = sort;
} else if (typeof sort === 'object') {
for (var property in sort) {
if (!isNaN(parseInt(sort[property]))) {
if (sort[property] < 0) {
fields.push('-' + property);
} else {
fields.push(property);
}
} else {
//property supplied is NaN; default to 1/ascending
fields.push(property);
}
}
}
fields.forEach(function (field) {
value = {};
if (field.startsWith('-')) {
value[field.substring(1)] = -1;
} else {
value[field] = 1;
}
self.sort(value);
});
return self;
};
};