Skip to content

Commit

Permalink
Merge pull request #10604 from amitbeck/Model_aggregate_options
Browse files Browse the repository at this point in the history
fix: allow calling `Model.aggregate()` with options
  • Loading branch information
vkarpov15 committed Aug 25, 2021
2 parents 0a38c79 + b05fe26 commit f8e9f91
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
3 changes: 2 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -731,8 +731,9 @@ declare module 'mongoose' {
interface Model<T, TQueryHelpers = {}, TMethods = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
new(doc?: AnyKeys<T> & AnyObject): EnforceDocument<T, TMethods>;

aggregate<R = any>(pipeline?: any[]): Aggregate<Array<R>>;
aggregate<R = any>(pipeline?: any[], options?: Record<string, unknown>): Aggregate<Array<R>>;
aggregate<R = any>(pipeline: any[], cb: Function): Promise<Array<R>>;
aggregate<R = any>(pipeline: any[], options: Record<string, unknown>, cb: Function): Promise<Array<R>>;

/** Base Mongoose instance the model uses. */
base: typeof mongoose;
Expand Down
14 changes: 12 additions & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4135,15 +4135,16 @@ Model.mapReduce = function mapReduce(o, callback) {
* @see Aggregate #aggregate_Aggregate
* @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
* @param {Array} [pipeline] aggregation pipeline as an array of objects
* @param {Object} [options] aggregation options
* @param {Function} [callback]
* @return {Aggregate}
* @api public
*/

Model.aggregate = function aggregate(pipeline, callback) {
Model.aggregate = function aggregate(pipeline, options, callback) {
_checkContext(this, 'aggregate');

if (arguments.length > 2 || get(pipeline, 'constructor.name') === 'Object') {
if (arguments.length > 3 || get(pipeline, 'constructor.name') === 'Object') {
throw new MongooseError('Mongoose 5.x disallows passing a spread of operators ' +
'to `Model.aggregate()`. Instead of ' +
'`Model.aggregate({ $match }, { $skip })`, do ' +
Expand All @@ -4155,9 +4156,18 @@ Model.aggregate = function aggregate(pipeline, callback) {
pipeline = [];
}

if (typeof options === 'function') {
callback = options;
options = null;
}

const aggregate = new Aggregate(pipeline || []);
aggregate.model(this);

if (options != null) {
aggregate.option(options);
}

if (typeof callback === 'undefined') {
return aggregate;
}
Expand Down

0 comments on commit f8e9f91

Please sign in to comment.