类型“Document<any, {}>”猫鼬打字稿上不存在属性“某物”

时间:2021-05-01 18:29:56

标签: node.js mongodb express mongoose mongoose-models

这是我在我的应用程序中使用 typescript 和 mongoose@5.12.6 实现的模型。在这里,我正在尝试为猫鼬实现一个方法,在我使用的 this.role 显示错误的方法中

Property 'role' does not exist on type 'Document<any, {}>'.

     { role: this.role },
                    ~~~~

我',想知道这个关键字如何在我实现的方法中起作用以及避免错误的方法

import { Document, Model, model, Schema, Types, Query } from "mongoose";
import jwt from "jsonwebtoken";

export interface IAdmin extends Document {
  username: string;
  firstname: string;
  lastname: string;
  mobile: string;
  email: string;
  password: string;
  role: string;
}

export interface IAdminDoc extends IAdmin, Document {
  generateAuthToken(): string;
}

export interface IAdminModel extends Model<IAdminDoc> {
  hashPassword(password: string): Promise<{ hashedPassword: string }>;
  comparePassword(
    inputPassword: string,
    hash: string
  ): Promise<{ isPasswordValid: boolean }>;
}

export const AdminSchema: Schema = new Schema(
  {
    username: {
      type: String,
      maxLength: 32,
      unique: true,
    },
    mobile: {
      type: String,
      maxLenght: 11,
      minLength: 11,
      unique: true,
      required: true,
    },
    firstname: {
      type: String,
      maxLength: 255,
      minLength: 2,
    },
    lastname: {
      type: String,
      maxLenght: 255,
      minLenght: 2,
    },
    email: {
      type: String,
      maxLenght: 255,
      minLenght: 6,
    },
    password: {
      type: String,
      maxLength: 255,
      minLength: 6,
      required: true,
    },
    role: {
      type: String,
      maxLength: 255,
      minLength: 2,
    },
  },
  {
    timestamps: {
      createdAt: "created_at",
      updatedAt: "updated_at",
    },
    autoIndex: true,
  }
);

AdminSchema.methods.generateAuthToken = function genAuthToken(): string {
  const adminToken = jwt.sign(
    { role: this.role },
    <string>process.env.jwtPrivateKeyAdmin
  );
  const token = jwt.sign(
    {
      somethingAsId: this._id,
      hereIsAdminToken: adminToken,
    },
    <string>process.env.jwtPrivateKey
  );
  return token;
};

export default model<IAdminDoc, IAdminModel>("Admin", AdminSchema);

0 个答案:

没有答案