类型"Document< any>"上不存在属性“密码" [英] Property 'password' does not exist on type 'Document<any>'

查看:87
本文介绍了类型"Document< any>"上不存在属性“密码"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TypeScript在Mongoose中创建一个用户架构,并且当我引用Schema的属性(例如 this.password )时,出现此错误:类型文档"上不存在属性密码" 当我使用pre()函数上的属性时,不会发生此错误,因为可以使用IUser接口键入它.我无法对我的方法做同样的事情,所以有什么办法可以解决这个问题?这很奇怪,因为我发现其他人使用相同的代码并且对他们有用,因此错误可能来自另一回事.在这里您可以找到带有错误的存储库:https://github.com/FaztWeb/restapi-jwt-ts

I am creating a User Schema in Mongoose using TypeScript, and when I'm referring to the properties of the Schema, like, this.password, I get this error: Property 'password' does not exist on type 'Document' This error does not happen when I am using the properties on the pre() function because I can type it with my IUser interface. I can't do the same for my methods, so is there any way to fix this?? It's weird because I find other people using the same code and it works for them, so maybe the error comes from another thing. Here you can find the repository with the error: 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 的位置添加通用声明:

You can add a generic declaration where you first create the Schema:

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

应该这样,以便在添加方法时对 this 进行精炼,使其包含 IUser .

That should make it such that this is refined to include IUser when you go to add the methods.

这篇关于类型"Document&lt; any&gt;"上不存在属性“密码"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆