首页 > 解决方案 > “文档”类型上不存在属性“密码”'

问题描述

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

输出错误

标签: typescriptmongoosemodelpropertiesdocument

解决方案


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

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

这应该使它在您添加方法时this被精炼以包含在内。IUser


推荐阅读