Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to register same mongoose hook for multiple methods in TypeScript?

Based on the answer in How to register same mongoose hook for multiple methods?

const hooks = [ 'find', 'findOne', 'update' ];

UserSchema.pre( hooks, function( next ) {
    // stuff
}

The code above works fine when not using TypeScript in strict mode. As soon as I enable strict mode, it complains: No overload matches this call.

How can I adjust the code to fix this? I can’t seem to find much documentation about it, most documentation just offers examples of how to do it for a single method instead of multiple at a time.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The inferred type of your hooks variable is string[]. Schema.pre has various overloads:

    /** Defines a pre hook for the model. */
    pre<T = THydratedDocumentType>(
      method: DocumentOrQueryMiddleware | DocumentOrQueryMiddleware[],
      options: SchemaPreOptions & { document: true; query: false; },
      fn: PreMiddlewareFunction<T>
    ): this;
    pre<T = Query<any, any>>(
      method: DocumentOrQueryMiddleware | DocumentOrQueryMiddleware[],
      options: SchemaPreOptions & { document: false; query: true; },
      fn: PreMiddlewareFunction<T>
    ): this;
    pre<T = THydratedDocumentType>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
    pre<T = THydratedDocumentType>(method: 'save', options: SchemaPreOptions, fn: PreSaveMiddlewareFunction<T>): this;
    pre<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
    pre<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
    pre<T = THydratedDocumentType>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
    pre<T = THydratedDocumentType>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
    pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
    pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
    pre<T = M>(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
    pre<T = M>(method: 'insertMany' | RegExp, options: SchemaPreOptions, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;

As the error message tells you, none of these accepts string[] as the method argument, because there are plenty of valid string values that are not valid method names.

However if you are more specific about your intentions, e.g. using the query middleware type:

  type MongooseQueryMiddleware = 'count' | 'estimatedDocumentCount' | 'countDocuments' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndReplace' | 'findOneAndUpdate' | 'remove' | 'replaceOne' | 'update' | 'updateOne' | 'updateMany';

you can satisfy the compiler (and get the values checked for any typos, e.g. it could tell you if findone was accidentally used instead of findOne):

import { type MongooseQueryMiddleware } from "mongoose";

// ...

const hooks: MongooseQueryMiddleware[] = ["find", "findOne", "update"];

UserSchema.pre(hooks, function (next) {
    // stuff
});

Alternatively, you could just inline the array:

UserSchema.pre(["find", "findOne", "update"], function (next) {
    // stuff
});

Note that using a type assertion, as suggested in your comment above, is not the right way to go about this. When you do that, rather than letting the compiler check the values you insist to it that they’re right, so it can’t catch typos for you:

const hooks = ["find", "findone", "update"] as MongooseQueryMiddleware[];
                    // ^^^^^^^^^

UserSchema.pre(hooks, function (next) {
    // stuff
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading