Typescript throws compilation error in Mongoose pre hook (Expected 1 arguments, but got 0)

Viewed 493

I am looking at example code which is placed inside the users.ts file, inside a User model.

userSchema.pre('save', async function(done) {
  if (this.isModified('password')) {
    const hashed = await Password.toHash(this.get('password'));
    this.set('password', hashed);
  }
  done();
});

However I get a compilation error when I try to build it:

src/models/user.ts(44,3): error TS2554: Expected 1 arguments, but got 0.

The error thrown looks to be the error with done(), as if I comment it out or change it to done(null) it goes through fine. However I'm not sure why this is happening as typescript states the following format for done():

(parameter) done: mongoose.HookNextFunction
(error?: mongoose.Error | undefined) => any

it should be able to accept an undefined value / empty inside done(), should it not?

Also changing

async function(done) ===> async function(done: any)

also resolves the issue.

The problem I am trying to resolve is why this is occurring as I have pulled the exact code from the example and have tried to run it, same typescript versions and type files.

"typescript": "^3.8.3"
"mongoose": "^5.9.7",
"@types/mongoose": "^5.7.8",

However for me it does not work, and I can't seem to understand why I have to put : any inside the parameter brackets to get it to work.

1 Answers

If you go to lecturer 138 of the course you are doing you will find the solution. For the rest of the people is because the new version of mongoose comes with its own type definitions and its overriding your @types/mongoose. To fix your issue you have to stick with last version of mongoose in 5.10 which is the version 5.10.19 so you should remove ^ or ~ from the version of that library in your package.json and use 5.10.19 version.

Related