【问题标题】:Property 'password' does not exist on type 'Document<any>'类型“文档<any>”上不存在属性“密码”
【发布时间】:2021-05-04 12:47:56
【问题描述】:

我正在使用 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);

OUTPUT ERROR

【问题讨论】:

    标签: typescript mongoose model properties document


    【解决方案1】:

    您可以在首先创建Schema 的位置添加通用声明:

    const userSchema = new Schema<IUser>({ ... });
    

    这应该使得this 在您添加方法时被细化为包含IUser

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 2019-05-07
      • 2021-05-09
      • 2021-02-08
      • 1970-01-01
      • 2019-09-20
      • 2018-09-09
      • 2019-12-31
      • 2022-12-17
      相关资源
      最近更新 更多