首页 > 解决方案 > 谁能帮我将代码转换为打字稿?

问题描述

我已经为模式实现了接口,但我不知道如何为猫鼬虚拟字段和方法定义类型

错误是:

'this' 隐含类型为 'any' 因为它没有类型 annotation.ts(2683)

'Document<any, any>'.ts(2339) 类型上不存在属性 'encryptPassword'

这是我的用户模型!

导入猫鼬,uuid 用于盐,crypto 用于加密。

import { model, Schema } from "mongoose";
import { v4 as uuid_v4 } from "uuid";
import crypto from "crypto";

定义 UserSchema 接口

export interface UserSchema extends Document {
  _id: string;
  username: string;
  email: string;
  hashed_password: string;
  salt: string;
  photo: {
    data: Buffer;
    contentType: string;
  };
  about: string;
}

定义架构

const userSchema: Schema = new Schema(
  {
    username: {
      type: String,
      trim: true,
      required: true,
    },
    email: {
      type: String,
      trim: true,
      required: true,
    },
    hashed_password: {
      type: String,
      require: true,
    },
    salt: {
      type: String,
    },
    photo: {
      data: Buffer,
      contentType: String,
    },
    about: {
      type: String,
      trim: true,
    },
  },
  { timestamps: true }
);

mongoose 虚拟字段和方法。

userSchema
  .virtual("password")
  .set(function (password) {
    //create temporary variable called _password
    this._password = password;
    //generate  a timestamp
    this.salt = uuid_v4();
    //encryptPassword()
    this.hashed_password = this.encryptPassword(password);
  })
  .get(function () {
    return this._password;
  });

//methods
userSchema.methods = {
  authenticate: function (plainText) {
    return this.encryptPassword(plainText) === this.hashed_password;
  },

  encryptPassword: function (password) {
    if (!password) return "";
    try {
      return crypto
        .createHmac("sha1", this.salt)
        .update(password)
        .digest("hex");
    } catch (err) {
      return "";
    }
  },
};

export default model<UserSchema>("User", userSchema);

你能帮我把它转换成打字稿吗?

标签: javascriptnode.jstypescriptmongoosemongoose-schema

解决方案


推荐阅读