Skip to content

Commit

Permalink
Added support for populate data
Browse files Browse the repository at this point in the history
  • Loading branch information
samkit5495 authored Dec 4, 2020
1 parent a8052f6 commit 9cf9535
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/models/plugins/paginate.plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const paginate = (schema) => {
* Query for documents with pagination
* @param {Object} [filter] - Mongo filter
* @param {Object} [options] - Query options
* @param {string} [options.populate] - populate data fields. Hierarchy of fields should be separated by (.). Multiple sorting criteria should be separated by commas (,)
* @param {string} [options.sortBy] - Sorting criteria using the format: sortField:(desc|asc). Multiple sorting criteria should be separated by commas (,)
* @param {number} [options.limit] - Maximum number of results per page (default = 10)
* @param {number} [options.page] - Current page (default = 1)
Expand All @@ -36,7 +37,20 @@ const paginate = (schema) => {
const skip = (page - 1) * limit;

const countPromise = this.countDocuments(filter).exec();
const docsPromise = this.find(filter).sort(sort).skip(skip).limit(limit).exec();
let docsPromise = this.find(filter).sort(sort).skip(skip).limit(limit);

if (options.populate) {
options.populate.split(',').forEach((populateOption) => {
docsPromise = docsPromise.populate(
populateOption
.split('.')
.reverse()
.reduce((a, b) => ({ path: b, populate: a }))
);
});
}

docsPromise = docsPromise.exec();

return Promise.all([countPromise, docsPromise]).then((values) => {
const [totalResults, results] = values;
Expand Down

0 comments on commit 9cf9535

Please sign in to comment.