forked from edwardhotchkiss/mongoose-paginate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (94 loc) · 2.5 KB
/
index.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
/**
* @package mongoose-paginate
* @param {Object} [query={}]
* @param {Object} [options={}]
* @param {Object|String} [options.select]
* @param {Object|String} [options.sort]
* @param {Object} [options.collation={}]
* @param {Array|Object|String} [options.populate]
* @param {Boolean} [options.lean=false]
* @param {Boolean} [options.leanWithId=true]
* @param {Number} [options.offset=0] - Use offset or page to set skip position
* @param {Number} [options.page=1]
* @param {Number} [options.limit=10]
* @param {Function} [callback]
* @returns {Promise}
*/
function paginate(query, options, callback) {
query = query || {};
options = Object.assign({}, paginate.options, options);
let select = options.select;
let sort = options.sort;
let populate = options.populate;
let collation = options.collation || {};
let lean = options.lean || false;
let leanWithId = options.leanWithId ? options.leanWithId : true;
let limit = options.limit ? options.limit : 10;
let page, offset, skip, promises;
if (options.offset) {
offset = options.offset;
skip = offset;
} else if (options.page) {
page = options.page;
skip = (page - 1) * limit;
} else {
page = 1;
offset = 0;
skip = offset;
}
if (limit) {
let docsQuery = this.find(query)
.select(select)
.collation(collation)
.sort(sort)
.skip(skip)
.limit(limit)
.lean(lean);
if (populate) {
[].concat(populate).forEach((item) => {
docsQuery.populate(item);
});
}
promises = {
docs: docsQuery.exec(),
count: this.count(query).exec()
};
if (lean && leanWithId) {
promises.docs = promises.docs.then((docs) => {
docs.forEach((doc) => {
doc.id = String(doc._id);
});
return docs;
});
}
}
promises = Object.keys(promises).map((x) => promises[x]);
return Promise.all(promises).then((data) => {
let result = {
docs: data.docs,
total: data.count,
limit: limit
};
if (offset !== undefined) {
result.offset = offset;
}
if (page !== undefined) {
result.page = page;
result.pages = Math.ceil(data.count / limit) || 1;
}
if (typeof callback === 'function') {
return callback(null, result);
}
let promise = new Promise();
promise.resolve(result);
return promise;
});
}
/**
* @param {Schema} schema
*/
module.exports = function(schema) {
schema.statics.paginate = paginate;
};
module.exports.paginate = paginate;