-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
38 lines (36 loc) · 1.03 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
const paginate = (schema) => {
schema.statics.paginate = async function (options, populate = '', query = {}) {
const { sortBy = 'createdAt', sortDirection = 'desc', page = 1, limit = 25 } = options;
const skip = (page - 1) * limit;
let docsQuery = this.find(query)
.sort({ [sortBy]: sortDirection })
.skip(skip)
.limit(limit);
if (populate) {
populate.split(' ').forEach((path) => {
docsQuery = docsQuery.populate(
path
.split('.')
.reverse()
.reduce((a, b) => ({ path: b, populate: a }))
);
});
}
const totalResultsPromise = this.countDocuments(query).exec();
const resultsPromise = docsQuery.lean().exec();
const [totalResults, rawResults] = await Promise.all([totalResultsPromise, resultsPromise]);
const results = rawResults.map((doc) => {
delete doc.activePaths;
delete doc.skipId;
return doc;
});
return {
results,
totalResults,
page,
limit: Math.min(limit, totalResults),
lastPage: Math.ceil(totalResults / limit)
};
};
};
module.exports = paginate;