Skip to content

Commit

Permalink
fix(aggregate): allow passing verbosity to Aggregate.prototype.expl…
Browse files Browse the repository at this point in the history
…ain()

Fix #11144
  • Loading branch information
vkarpov15 committed Jan 15, 2022
1 parent 2d6bbf9 commit fd1abea
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2817,6 +2817,7 @@ declare module 'mongoose' {

/** Execute the aggregation with explain */
explain(callback?: Callback): Promise<any>;
explain(verbosity?: string, callback?: Callback): Promise<any>;

/** Combines multiple aggregation pipelines. */
facet(options: PipelineStage.Facet['$facet']): this;
Expand Down
37 changes: 26 additions & 11 deletions lib/aggregate.js
Original file line number Diff line number Diff line change
Expand Up @@ -710,12 +710,17 @@ Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) {
*
* Model.aggregate(..).explain(callback)
*
* @param {String} verbosity
* @param {Function} callback
* @return {Promise}
*/

Aggregate.prototype.explain = function(callback) {
Aggregate.prototype.explain = function(verbosity, callback) {
const model = this._model;
if (typeof verbosity === 'function') {
callback = verbosity;
verbosity = null;
}

return promiseOrCallback(callback, cb => {
if (!this._pipeline.length) {
Expand All @@ -733,24 +738,34 @@ Aggregate.prototype.explain = function(callback) {
});
}

this.options.explain = true;

model.collection.aggregate(this._pipeline, this.options, (error, cursor) => {
if (error != null) {
const _opts = { error: error };
return model.hooks.execPost('aggregate', this, [null], _opts, error => {
cb(error);
});
}
cursor.explain((error, result) => {
const _opts = { error: error };
return model.hooks.execPost('aggregate', this, [result], _opts, error => {
if (error) {
return cb(error);
}
return cb(null, result);
if (verbosity != null) {
cursor.explain(verbosity, (error, result) => {
const _opts = { error: error };
return model.hooks.execPost('aggregate', this, [result], _opts, error => {
if (error) {
return cb(error);
}
return cb(null, result);
});
});
});
} else {
cursor.explain((error, result) => {
const _opts = { error: error };
return model.hooks.execPost('aggregate', this, [result], _opts, error => {
if (error) {
return cb(error);
}
return cb(null, result);
});
});
}
});
});
}, model.events);
Expand Down

0 comments on commit fd1abea

Please sign in to comment.