From b90acd46c0d70c664ef5270e64a584f124558264 Mon Sep 17 00:00:00 2001 From: Srinand Balaji Date: Wed, 25 Aug 2021 19:15:31 -0700 Subject: [PATCH] feat: add support for aggregation `hint`s This module supports `hint`s for `find` queries, and this commit adds logic to support `hint`s for `aggregation`s. --- src/aggregate.js | 7 ++++++- test/aggregate.test.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/aggregate.js b/src/aggregate.js index 5eed932..100f108 100644 --- a/src/aggregate.js +++ b/src/aggregate.js @@ -33,6 +33,7 @@ const config = require('./config'); * -previous {String} The value to start querying previous page. * -after {String} The _id to start querying the page. * -before {String} The _id to start querying previous page. + * -options {Object} Aggregation options */ module.exports = async function aggregate(collection, params) { params = _.defaults(await sanitizeParams(collection, params), { aggregation: [] }); @@ -57,6 +58,10 @@ module.exports = async function aggregate(collection, params) { params.aggregation.splice(index + 1, 0, { $sort }); params.aggregation.splice(index + 2, 0, { $limit: params.limit + 1 }); + // Aggregation options: + // https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#aggregate + // https://mongodb.github.io/node-mongodb-native/4.0/interfaces/aggregateoptions.html + const options = params.options || {}; /** * IMPORTANT * @@ -66,7 +71,7 @@ module.exports = async function aggregate(collection, params) { * * See mongo documentation: https://docs.mongodb.com/manual/reference/collation/#collation-and-index-use */ - const options = config.COLLATION ? { collation: config.COLLATION } : undefined; + if (config.COLLATION) options.collation = config.COLLATION; // Support both the native 'mongodb' driver and 'mongoist'. See: // https://www.npmjs.com/package/mongoist#cursor-operations diff --git a/test/aggregate.test.js b/test/aggregate.test.js index 0b68ed7..c163e8b 100644 --- a/test/aggregate.test.js +++ b/test/aggregate.test.js @@ -85,6 +85,14 @@ describe('aggregate', () => { name: 'saturn', }, ]), + t.db.collection('test_aggregation_lookup').ensureIndex( + { + name: 'text', + }, + { + name: 'test_index', + } + ), t.db.collection('test_aggregation_sort').insert([ { name: 'Alpha', @@ -668,4 +676,33 @@ describe('aggregate', () => { ]); }); }); + + describe('aggregation options', () => { + let spy; + beforeEach(() => { + spy = jest.spyOn(paging, 'aggregate'); + }); + + afterEach(() => { + spy.mockRestore(); + }); + + it('invokes aggregate with a `hint` if one is passed in via params object', async () => { + const collection = t.db.collection('test_aggregation_lookup'); + + await paging.aggregate(collection, { + aggregation: [ + { + $sort: { name: 1 }, + }, + ], + hint: 'test_index', + }); + + expect(spy).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ hint: 'test_index' }) + ); + }); + }); });