Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,13 @@ const queryMiddlewareFunctions = queryOperations.concat([
]);

exports.queryMiddlewareFunctions = queryMiddlewareFunctions;

/*!
* ignore
*/

const aggregateMiddlewareFunctions = [
'aggregate'
];

exports.aggregateMiddlewareFunctions = aggregateMiddlewareFunctions;
9 changes: 7 additions & 2 deletions lib/helpers/model/applyStaticHooks.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
'use strict';

const middlewareFunctions = require('../../constants').queryMiddlewareFunctions;
const promiseOrCallback = require('../promiseOrCallback');
const { queryMiddlewareFunctions, aggregateMiddlewareFunctions } = require('../../constants');

const middlewareFunctions = [
...queryMiddlewareFunctions,
...aggregateMiddlewareFunctions
];

module.exports = function applyStaticHooks(model, hooks, statics) {
const kareemOptions = {
Expand All @@ -10,7 +15,7 @@ module.exports = function applyStaticHooks(model, hooks, statics) {
};

hooks = hooks.filter(hook => {
// If the custom static overwrites an existing query middleware, don't apply
// If the custom static overwrites an existing query/aggregate middleware, don't apply
// middleware to it by default. This avoids a potential backwards breaking
// change with plugins like `mongoose-delete` that use statics to overwrite
// built-in Mongoose functions.
Expand Down
30 changes: 30 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const assert = require('assert');
const { once } = require('events');
const random = require('./util').random;
const util = require('./util');
const model = require('../lib/model');

const mongoose = start.mongoose;
const Schema = mongoose.Schema;
Expand Down Expand Up @@ -5861,6 +5862,35 @@ describe('Model', function() {

});

it('custom statics that overwrite aggregate functions dont get hooks by default (gh-14903)', async function() {

const schema = new Schema({ name: String });

schema.statics.aggregate = function(pipeline) {
return model.aggregate.apply(this, [pipeline]);
};

let called = 0;
schema.pre('aggregate', function(next) {
++called;
next();
});
const Model = db.model('Test', schema);

await Model.create({ name: 'foo' });

const res = await Model.aggregate([
{
$match: {
name: 'foo'
}
}
]);

assert.ok(res[0].name);
assert.equal(called, 1);
});

it('error handling middleware passes saved doc (gh-7832)', async function() {
const schema = new Schema({ _id: Number });

Expand Down