【问题标题】:An outer value of 'this' is shadowed by this container with Mongoose Schema Typescript此容器使用 Mongoose Schema Typescript 遮蔽了“this”的外部值
【发布时间】:2021-05-16 00:20:11
【问题描述】:

对于 MongoDB 的架构验证器,我有以下内容:{

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

我收到以下错误:

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

这是在我的User.ts 文件中定义的。一切都按预期工作,但这个 Typescript 错误阻止 CI 继续。有没有办法解决这个问题(没有双关语)。

【问题讨论】:

    标签: mongodb typescript mongoose


    【解决方案1】:

    试试:

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

    您可以使用您的类型而不是“任何”。

    文档链接:https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters

    【讨论】:

    • 这行得通!在您回答之前,我实际上使用了一个插件,该插件更改了默认的 unique 字段行为以显示为正常的验证错误,以便我可以将验证错误消息直接放入架构本身。
    猜你喜欢
    • 2019-10-05
    • 2019-12-21
    • 2019-05-19
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2011-10-11
    • 2021-12-07
    • 2020-08-28
    相关资源
    最近更新 更多