Answer a question

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).

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

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐