Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow calling Model.aggregate() with options #10604

Merged
merged 2 commits into from
Aug 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion index.d.ts
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
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