如何解决类型“Document<any>”
我正在使用 TypeScript 在 Mongoose 中创建用户架构,当我提到架构的属性时,例如 this.password,我收到此错误: “文档”类型不存在“密码”属性 当我在 pre() 函数上使用属性时不会发生此错误,因为我可以使用 IUser 界面键入它。我不能对我的方法做同样的事情,所以有什么办法可以解决这个问题吗?这很奇怪,因为我发现其他人使用相同的代码并且它对他们有效,所以可能错误来自另一件事。在这里你可以找到错误的存储库:https://github.com/FaztWeb/restapi-jwt-ts
import { model,Schema,Document } from "mongoose";
import bcrypt from "bcrypt";
export interface IUser extends Document {
email: string;
password: string;
comparePassword: (password: string) => Promise<Boolean>
};
const userSchema = new Schema({
email: {
type: String,unique: true,required: true,lowercase: true,trim: true
},password: {
type: String,required: true
}
});
userSchema.pre<IUser>("save",async function(next) {
const user = this;
if (!user.isModified("password")) return next();
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password,salt);
user.password = hash;
next();
});
userSchema.methods.comparePassword = async function(password: string): Promise<Boolean> {
return await bcrypt.compare(password,this.password);
};
export default model<IUser>("User",userSchema);
解决方法
您可以在首次创建 Schema
的位置添加通用声明:
const userSchema = new Schema<IUser>({ ... });
这应该使 this
在您添加方法时经过改进以包含 IUser
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。