Typescript 财产';密码';不存在于类型';文件<;任何>';

Typescript 财产';密码';不存在于类型';文件<;任何>';,typescript,mongoose,model,properties,document,Typescript,Mongoose,Model,Properties,Document,我正在使用TypeScript在Mongoose中创建一个用户模式,当我引用该模式的属性时,如this.password,我得到以下错误: 类型“文档”上不存在属性“密码” 在使用pre()函数的属性时不会发生此错误,因为我可以使用IUser接口键入它。我不能对我的方法做同样的事情,所以有没有办法解决这个问题??这很奇怪,因为我发现其他人使用相同的代码,而且对他们有效,所以可能错误来自另一件事。您可以在此处找到包含错误的存储库:https://github.com/FaztWeb/restapi

我正在使用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);
从“mongoose”导入{model,Schema,Document};
从“bcrypt”导入bcrypt;
导出接口IUser扩展文档{
电子邮件:字符串;
密码:字符串;
comparePassword:(密码:string)=>Promise
};
const userSchema=新模式({
电邮:{
类型:字符串,
独一无二:没错,
要求:正确,
小写:true,
修剪:对
},
密码:{
类型:字符串,
必填项:true
}
});
userSchema.pre(“保存”,异步函数(下一步){
const user=this;
如果(!user.isModified(“password”))返回next();
常量盐=等待B晶型盐(10);
const hash=await bcrypt.hash(user.password,salt);
user.password=hash;
next();
});
userSchema.methods.comparePassword=异步函数(密码:字符串):承诺{
return wait bcrypt.compare(密码,this.password);
};
导出默认模型(“用户”,userSchema);

您可以在第一次创建
架构的位置添加一个通用声明

const userSchema = new Schema<IUser>({ ... });
constuserschema=newschema({…});
这样,当您添加方法时,
将被细化为包含
IUser