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(model): skip applying static hooks by default if static name conflicts with aggregate middleware #14904

Conversation

dragontaek-lee
Copy link
Contributor

@dragontaek-lee dragontaek-lee commented Sep 22, 2024

Fix #14903

Summary

Make it so that if the custom static overwrites an existing aggregate middleware, don't apply middleware to it by default. This should be achieved by filtering custom static-named aggregates in applyStaticHooks.js.

Furthermore, aside from this PR, I believe we should extend this filtering not only to query and aggregation middleware but also to other Mongoose middlewares, including Document and Model middleware. Does that make sense? If so, I would like to create another PR for this work.

Examples

schema.statics.aggregate = function(pipeline) {
    let match = { $match: { deleted: { '$ne': false } } };

    if (pipeline.length && pipeline[0].$match) {
        pipeline[0].$match.deleted = { '$ne': false };
    } else {
        pipeline.unshift(match);
    }

    const query = Model.aggregate.apply(this, [pipeline]);
    return query;
};

Assume that the static method overwrites the built-in Mongoose aggregate function.

schema.pre('aggregate', function(next) {
    console.log(this);
    next();
});

schema.post('aggregate', function() {
    console.log(this);
});

In this situation, also assume that there are pre and post hooks for aggregate.

With this PR, when a custom static method overwrites an existing aggregate middleware as described above, the middleware is not applied by default. As a result, the this context type in pre/post hooks is correctly set to Aggregate, as intended.

@vkarpov15 vkarpov15 added this to the 8.6.4 milestone Sep 23, 2024
Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks 👍

@vkarpov15
Copy link
Collaborator

And yes you can create a separate PR to apply this filtering to other middleware types.

@vkarpov15 vkarpov15 merged commit f9ca745 into Automattic:master Sep 23, 2024
24 checks passed
@dragontaek-lee
Copy link
Contributor Author

@vkarpov15
Thanks for the review and comments! 👍
As per your guidance, I’ve created a separate PR (#14908). Please feel free to check it at your convenience!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

hook is not of type Aggregate
2 participants