I am working on a authentification project using typescript and mongoose as my database. Whilst writing my middleware code that should hash the password before it gets inserted into the mongoose database i came across this typescript error:
This expression is not callable. Type 'SaveOptions' has no call signatures.ts(2349)
How can I solve this?
Below is the code. I get this error on both next().
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
return next();
}
this.password = await hashValue(this.password);
return next();
});
I have tried next: HookNextFunction which unhighlights next()but highlights HookNextFunction with Cannot use namespace 'HookNextFunction' as a type.
I have also installed @types/mongoose. In my entire codebase these are the only two errors. Please inform me if more code is needed. Below is also my tsconfig:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "./",
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules"]
}
According to the high-level
documentation and the JSDoc
comment above the pre
method,
this callback does not get passed a next function (it's given an
options object instead).
If your callback is async, Mongoose will wait until its Promise resolves to
execute additional middleware. There's no need to
coordinate things yourself with a next function as in Express.
So you can probably write your code like this:
userSchema.pre("save", async function () {
if (this.isModified("password")) {
this.password = await hashValue(this.password);
}
});