Mongoose hooks not working with Typescript

Viewed 2921

So does anyone know why I might be getting a Typescript error when using a mongoose hook and referencing this. I am not using arrow functions, and I know about the lexical scoping issue with that, but even with anonymous functions like this:

UserSchema.pre("save", function(next) {
    console.log(this.password);
    next();
});

The exact error message is

'this' implicitly has type 'any' because it does not have a type annotation.

Anyone know how to get around this?

BTW I'm using Typescript 2.5.2 / NodeJS 8.2.1

Thanks!

2 Answers

try this:

import {HydratedDocument} from 'mongoose'
schema.pre<HydratedDocument<IUser>>('save',function(next){})

instead of IUser use your interface .

Related