I created some test cases to reproduce this issue in the reproduction repository.
The code can be found in index.js, test/aggregate.middleware.test.js, or test/query.middleware.test.js.
Tests and scripts can also be run using the npm commands mentioned in the README.
In this situation, also assume that there are pre and post hooks for aggregate.
Test 1
both the custom static method and the built-in Mongoose aggregate hooks are executed and both the pre and post hooks are called twice
Test 2
this context differs between the custom static method and the built-in aggregate function.
in the first pre-hook and the second post-hook call, this context is not an instance of Aggregate, but in the second pre-hook and the first post-hook call, it becomes an instance of Aggregate.
Prerequisites
Mongoose version
8.6.1
Node.js version
20.10.0
MongoDB server version
7.0.9
Typescript version (if applicable)
No response
Description
this context in hooks are not of type Aggregate.
This issue arises when custom static methods overwrite built-in aggregate functions. (as seen in the implementation in
mongoose-delete
)This issue is similar to the past one (https://github.com/Automattic/mongoose/issues/7790), where the context in hooks was not of type Query. I noticed that it has been fixed in this PR (https://github.com/Automattic/mongoose/commit/f848b54d33cc5f61be3b1f0539370f9c43d9d4e2), which filters custom static methods that overwrite existing query middleware in
applyStaticHooks.js
.Steps to Reproduce
I created a minimum reproduction repository. (https://github.com/dragontaek-lee/mongoose-staticHooks-overwrite-support-more-cases)
I created some test cases to reproduce this issue in the reproduction repository. The code can be found in
index.js
,test/aggregate.middleware.test.js
, ortest/query.middleware.test.js
. Tests and scripts can also be run using the npm commands mentioned in the README.The summarized reproduction code is as follows:
Assume that the static method overwrites the built-in Mongoose aggregate function.
In this situation, also assume that there are pre and post hooks for aggregate.
Test 1
Test 2
this
context is not an instance of Aggregate, but in the second pre-hook and the first post-hook call, it becomes an instance of Aggregate.Expected Behavior
Since the issues with query middleware were fixed in this PR (https://github.com/Automattic/mongoose/commit/f848b54d33cc5f61be3b1f0539370f9c43d9d4e2), it is expected that if a custom static method overwrites an existing aggregate middleware, the middleware should not be applied by default, just as it works with query middleware.
I’m going to submit the PR right away for this.