4

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!

Eric
  • 328
  • 4
  • 13
  • 1
    This question might help: https://stackoverflow.com/questions/41944650/this-implicitly-has-type-any-because-it-does-not-have-a-type-annotation – Steve Holgado Sep 12 '17 at 21:07

3 Answers3

8

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.

Harry
  • 353
  • 2
  • 9
  • This works! It threw me off because I didn't see a callback signature that allowed for passing context through as a typed parameter. Either way, thanks! – Eric Sep 13 '17 at 17:45
0

try this:

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

instead of IUser use your interface .

jalal
  • 21
  • 2
0

Best Typescript example with ts-mongoose:-

import { ExtractDoc, Type, createSchema, typedModel } from 'ts-mongoose';

const UserSchema = createSchema(
  {
    email: Type.string({ required: true, unique: true }),
    firstName: Type.string({ required: true }),
    lastName: Type.string({ required: true }),
  }
);

const User = typedModel(CONSTANTS.MODEL_NAME.USER, UserSchema, undefined, undefined, {
  updateById: function (id: string, data: {}) {
    return this.findByIdAndUpdate(id, data, { new: true });
  },

  findByUserId: function (id: string) {
    return this.findOne({ _id: id });
  },
});

type UserDoc = ExtractDoc<typeof UserSchema>;

UserSchema.pre('update', function (this: UserDoc, next) {
let phone = this.phone;
  phone = sanitizePhoneNumber(phone);
  this.save();
  next();
});