Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An outer value of 'this' is shadowed by this container with Mongoose Schema Typescript

I have the following for a schema validator for MongoDB:{

UserSchema.path('email').validate(async function (email: string) {
  const count = await User.count({ email, _id: { $ne: this._id } })
  return !count
}, 'Email already exists')

I'm getting the following error:

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
User.ts(171, 35): An outer value of 'this' is shadowed by this container.

This is defined in my User.ts file. Everything works exactly as expected but this Typescript error is blocking CI from continuing. Is there anyway to get around this (no pun intended).

like image 373
SKeney Avatar asked Feb 12 '21 08:02

SKeney


1 Answers

Try:

UserSchema.path('email').validate(async function (this:any, email: string) {
  const count = await User.count({ email, _id: { $ne: this._id } })
  return !count
}, 'Email already exists')

You can use your type instead of "any".

And the link to the docu: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters

like image 75
Sonatai Avatar answered Sep 24 '22 04:09

Sonatai