Search code examples
node.jstypescriptmongoosemongoose-schema

Mongoose post hook Type error in TypeScript


I am using mongoose and typescript, when I call updateOne() on the model I want to use

someSchema.post<Query>('updateOne', function(doc: IsomeDoc) {
    console.log(this)
}

The problem is that this is of type Query if I suppress typescript checker and ignore as it give me an error:

Generic type 'Query<ResultType, DocType, THelpers>' requires between 2 and 3 type arguments.

This is my schema

const someSchema = new Schema(
  {
    _id: { type: String, required: true },
    status: { type: String },
  },
  { timestamps: true }
)

How can I get the correct type for this inside the function? After lots of searching there is barely any use of post hook with typescript and mongoose. What is ResultType?

Edit:

After seeing @gregooroo's answer I was able to get past Query by making it Query<IsomeDoc, IsomeDoc> but it does not give me the correct type for this object.


Solution

  • For query middlewares you need to construct a Query type with a generic type of what this query should return

    
    someSchema.post<Query<IsomeDoc, IsomeDoc>>('updateOne', function(doc) {
        console.log(this)
    }