Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose hooks not working with Typescript

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!

like image 819
Eric Avatar asked Oct 31 '25 17:10

Eric


1 Answers

Try this:

schema.pre("save", function(this: UserModel, next: any) {
  console.log(this.password);
  next();
});

I think you're getting the error because you probably have a typescript config which checks for implicit any. If you type 'this' in the arguments of the hook function, the error should be resolved.

like image 116
Harry Avatar answered Nov 03 '25 10:11

Harry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!