【问题标题】:Typescript & Mongoose - "this" not available in instance methodsTypescript & Mongoose - "this" 在实例方法中不可用
【发布时间】:2021-04-18 15:11:39
【问题描述】:

我目前正在将我的 API 从 JS 转换为 TS。但是,我在使用猫鼬和打字稿时遇到了一些困难。具体来说,this 在我的实例方法中不可用。

我的代码:

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

这会产生以下错误,因为this 指的是函数而不是实际文档:

“函数”类型的参数不能分配给“字符串”类型的参数。

但是,根据Mongoose's documentation,应该不会有错误,因为this 应该参考实际文档。

这实际上指的是什么:

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

我如何定义我的架构:

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

我的方法适用于 JS,所以我知道它与 TypeScript 有关。 Mongoose documentation 确认我的实现是定义实例方法的正确方法,所以我很困惑为什么它不起作用。

是否有一种我不知道的在 mongoose 中声明和使用实例方法的特定 TS 方式?

任何帮助将不胜感激!

【问题讨论】:

  • “'Function' 类型的参数不能分配给'string' 类型的参数。” 非常清楚地告诉你你正在传递一个函数,其中需要一个字符串.错误的依据是什么?你调用的函数/方法的定义是什么?论据的定义是什么?
  • 可以试试简写。AccountSchema.methods.comparePassword = async (candidatePassword: string): boolean => { const isMatch = await bcrypt.compare(candidatePassword, this.password);返回是匹配; };
  • @T.J.Crowder 首先不应该出现这样的错误,因为根据 Mongoose 的文档,“this”应该指的是实际文档而不是函数
  • @user906573 不起作用,因为它会阻止它被绑定(根据 Mongoose 的文档。我收到一条错误消息,“this”可能未定义。
  • @T.J.Crowder 更新了我的问题,现在应该更清楚了

标签: node.js typescript mongoose


【解决方案1】:

我所需要的只是该函数的this 参数。这在 TS 中比较特殊,在函数中指定了this 的类型。

像这样:

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

this 参数未显式传递,因此新参数不会改变函数的调用方式。

【讨论】:

猜你喜欢
  • 2022-01-22
  • 2023-02-01
  • 2020-03-26
  • 1970-01-01
  • 2016-08-25
  • 2021-01-23
  • 2015-06-22
  • 2018-09-15
相关资源
最近更新 更多