Node.js 打字稿&;猫鼬;这";实例方法中不可用
我目前正在将我的API从JS转换为TS。然而,我在mongoose和typescript方面遇到了一些困难。具体来说,Node.js 打字稿&;猫鼬;这";实例方法中不可用,node.js,typescript,mongoose,Node.js,Typescript,Mongoose,我目前正在将我的API从JS转换为TS。然而,我在mongoose和typescript方面遇到了一些困难。具体来说,此在我的实例方法中不可用 我的代码: AccountSchema.methods.comparePassword = async function (candidatePassword: string) { const isMatch = await bcrypt.compare(candidatePassword, this.password); return isMa
此
在我的实例方法中不可用
我的代码:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};
this: {
[name: string]: Function;
}
const AccountSchema = new mongoose.Schema<IAccount>({...})
async function (this: IAccount, candidatePassword: string) { ... }
生成以下错误,因为该引用的是函数而不是实际文档:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};
this: {
[name: string]: Function;
}
const AccountSchema = new mongoose.Schema<IAccount>({...})
async function (this: IAccount, candidatePassword: string) { ... }
“Function”类型的参数不能分配给“string”类型的参数
但是,根据,不应该有错误,因为此
应参考实际文档
这实际上指的是什么:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};
this: {
[name: string]: Function;
}
const AccountSchema = new mongoose.Schema<IAccount>({...})
async function (this: IAccount, candidatePassword: string) { ... }
我如何定义我的模式:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};
this: {
[name: string]: Function;
}
const AccountSchema = new mongoose.Schema<IAccount>({...})
async function (this: IAccount, candidatePassword: string) { ... }
const AccountSchema=new mongoose.Schema({…})
我的方法与JS配合得很好,所以我知道它与TypeScript有关。确认我的实现是定义实例方法的正确方法,所以我很困惑为什么它不起作用
在mongoose中是否有我不知道的声明和使用实例方法的特定TS方式
任何帮助都将不胜感激 我所需要的就是该函数上的
这个参数。这在TS中是特殊的,并指定函数中此
的类型
像这样:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};
this: {
[name: string]: Function;
}
const AccountSchema = new mongoose.Schema<IAccount>({...})
async function (this: IAccount, candidatePassword: string) { ... }
此
参数不是显式传递的,因此新参数不会更改函数的调用方式。类型为'function'的参数不可分配给类型为'string'的参数。它非常清楚地告诉您传递的函数应该是字符串。错误在哪一个参数上?您正在调用的函数/方法的定义是什么?参数的定义是什么?可以尝试速记.AccountSchema.methods.comparePassword=async(candidatePassword:string):boolean=>{const isMatch=await bcrypt.compare(candidatePassword,this.password);返回isMatch;}@T.J.Crowder一开始甚至不应该有这样的错误,因为根据Mongoose的文档,“这个”应该指的是实际的文档,而不是function@user906573这不起作用,因为它阻止了绑定(根据Mongoose的文档,我收到一条错误消息“this”可能未定义。@T.J.Crowder更新了我的问题,现在应该更清楚了