I am currently trying to add a static method to my mongoose schema but I can\'t find the reason why it doesn\'t work this way.
My model:
import * as
So the one with 70 updates I also gave an upvote. But it is not a complete solution. He uses a trivial example based on the OP. However, more often than not when we use statics and methods in order to extend the functionality of the model, we want to reference the model itself. The problem with his solution is he using a callback function which means the value of this will not refer to the class context but rather a global.
The first step is to invoke the statics property rather than pass the property as an argument to the static function:
schema.statics.hashPassword
Now we cannot assign an arrow function to this member, for this inside the arrow function will still refer to the global object! We have to use function expression syntax in order to capture this in the context of the model:
schema.statics.hashPassword = async function(password: string): Promise {
console.log('the number of users: ', await this.count({}));
...
}