mongoose属性'password'在类型'Document<any>上不存在

-- userSchema.ts 接口

import mongoose, { Schema, Document } from "mongoose";
import moment from "moment";
import bcrypt from "bcrypt";

export interface UserDoc extends Document {
  name: {
    type: string;
    required: boolean;
  };
  email: {
    type: string;
    required: boolean;
  };
  password: {
    type: string;
    required: boolean;
  };
  dateJoined: {
    type: string;
    default: string;
  };
}

const userSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },

  dateJoined: {
    type: String,
    default: moment().format("MMMM Do YYYY"),
  },
});

我创建了我的用户模型,我遇到的问题是使用 bcrypt创建matchPassword方法来比较enterPassword参数与数据库中的密码

userSchema.methods.matchPassword = async function (enteredPassword) {
  return await bcrypt.compare(enteredPassword, this.password); ***
};

userSchema.pre("save", async function (next) {
  if (this.isModified("password")) {
    next();
  }

  const salt = bcrypt.genSalt(10);

  *** this.password = await bcrypt.hash(this.password, await salt); ***
});

const User = mongoose.model("User", userSchema);

错误信息如下:

Property 'password' does not exist on type 'Document<any>'.

并且此错误出现在this.password 的每个实例上,以 *** 突出显示

我之前在 Javascript 中使用过相同的方法,所以我不知道为什么它在打字稿上不起作用,以及如何将this.password绑定到 Mongoose 文档

谢谢

回答

看起来@Mohammad 已经帮助你bcrypt实现了。我可以帮你解决打字稿错误!

UserDoc是一个打字稿接口,所以它不应该有像required. 它应该只描述UserDoc对象的类型。默认情况下需要属性。我们使用?:if 它们是可选的,但看起来这里都是必需的。

export interface UserDoc extends Document {
  name: string;
  email: string;
  password: string;
  dateJoined: string;
  matchPassword: (pw: string) => Promise<boolean>
}

当您创建userSchema,你告诉打字稿,这是一个模式UserDoc-不是随便什么Document-通过设定的通用变量Schema构造函数UserDoc

const userSchema = new Schema<UserDoc>({ ...

这清除了错误,userSchema.methods.matchPassword因为我们知道这this.password是一个string. 我们也知道这enteredPasswordstring因为我们matchPasswordUserDoc接口中定义了这个方法的参数。

出于某种原因,该pre方法不会自动知道我们的文档类型。但是该pre方法本身是一个通用函数,因此我们可以再次指定我们的 doc 是一个UserDoc.

userSchema.pre<UserDoc>( ...

这很愚蠢,但我们必须在创建模型时再次指定泛型。

const User = mongoose.model<UserDoc>("User", userSchema);

现在User有类型mongoose.Model<UserDoc, {}>,你调用的任何方法都应该返回 aUserDoc而不仅仅是 a Document


以上是mongoose属性'password'在类型'Document&lt;any&gt;上不存在的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>