Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

353
Views
Typescript & Mongoose - "this" not available in instance methods

I am currently converting my API from JS to TS. However, I'm having some difficulties with mongoose & typescript. Specifically, this is not available inside my instance methods.

My code:

AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
  const isMatch = await bcrypt.compare(candidatePassword, this.password);
  return isMatch;
};

Which generates the following error as this refers to the function rather than the actual document:

Argument of type 'Function' is not assignable to parameter of type 'string'.

However, according to Mongoose's documentation, there shouldn't be an error as this should refer to the actual document.

What this actually refers to:

this: {
    [name: string]: Function;
}

How I defined my schema:

const AccountSchema = new mongoose.Schema<IAccount>({...})

My approach worked just fine with JS, so I know it has something to do with TypeScript. Mongoose documentation confirms that my implementation is the right way to define instance methods, so I'm quite confused why it doesn't work.

Is there a specific TS way of declaring & using instance methods in mongoose that I don't know of?

Any help would be greatly appreciated!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

All I needed was a this parameter on that function. That's special in TS, and specifies the type of this within the function.

Like so:

async function (this: IAccount, candidatePassword: string) { ... }

this parameters are not passed explicitly, so the new parameter doesn't change how the function is called.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!