Skip to content

Commit

Permalink
Add projection option to mongoose pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
zarathustra323 committed Jul 6, 2018
1 parent aed3ca5 commit d7668d8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/pagination.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@ class Pagination {
* @param {object} params.sort The sort parameters
* @param {string} params.sort.field The sort field name.
* @param {string} params.sort.order The sort order. Either 1/-1 or asc/desc.
* @param {?object} params.projection The field projection (fields to return).
* @param {object} options Additional sort and limit options. See the corresponding classes.
*/
constructor(Model, { criteria = {}, pagination = {}, sort = {} } = {}, options = {}) {
constructor(Model, {
criteria = {},
pagination = {},
sort = {},
projection,
} = {}, options = {}) {
this.promises = {};

// Set the Model to use for querying.
Expand All @@ -36,6 +42,9 @@ class Pagination {
// Set the sort criteria.
const { field, order } = sort;
this.sort = new Sort(field, order, options.sort);

// Set the projection.
this.projection = projection;
}

/**
Expand Down Expand Up @@ -63,7 +72,7 @@ class Pagination {
getEdges() {
const run = async () => {
const criteria = await this.getQueryCriteria();
const docs = await this.Model.find(criteria)
const docs = await this.Model.find(criteria, this.projection)
.sort(this.sort.value)
.limit(this.first.value)
.collation(this.sort.collation)
Expand Down
25 changes: 25 additions & 0 deletions test/pagination.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,31 @@ describe('pagination', function() {
sinon.assert.calledOnce(Pagination.prototype.getQueryCriteria);
});

it('should apply the projection', async function() {
const pagination = { first: 10 };
const projection = { name: 1 };
const paginated = new Pagination(Model, { pagination, projection });
const r1 = await paginated.getEdges();
r1.forEach((edge, i) => {
const { node } = edge;
expect(node.deleted).to.be.undefined;
expect(node.name).to.equal(data[i].name);
});
});

[{}, undefined].forEach((projection) => {
it(`should return all fields when the projection is '${projection}'`, async function() {
const pagination = { first: 10 };
const paginated = new Pagination(Model, { pagination, projection });
const r1 = await paginated.getEdges();
r1.forEach((edge, i) => {
const { node } = edge;
expect(node.deleted).to.equal(data[i].deleted);
expect(node.name).to.equal(data[i].name);
});
});
});

});

describe('#findCursorModel', function() {
Expand Down

0 comments on commit d7668d8

Please sign in to comment.