diff --git a/src/models/plugins/paginate.plugin.js b/src/models/plugins/paginate.plugin.js index 392ccd50..b42745c3 100644 --- a/src/models/plugins/paginate.plugin.js +++ b/src/models/plugins/paginate.plugin.js @@ -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) @@ -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;