【问题标题】:Create mongoose schema methods using TypeScript使用 TypeScript 创建猫鼬模式方法
【发布时间】:2021-04-16 09:55:14
【问题描述】:

我尝试为用户架构创建方法 hashPassword。

schema.method("hashPassword", function (): void {
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(this.password, salt);

  this.password = hash;
});

密码错误Property 'password' does not exist on type 'Document<any>'.

这是我的文件

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

/**
 * This interface should be the same as JWTPayload declared in types/global.d.ts file
 */
export interface IUser extends Document {
  name: string;
  email: string;
  username: string;
  password: string;
  confirmed: boolean;
  hashPassword: () => void;
  checkPassword: (password: string) => boolean;
}

// User schema
const schema = new Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
    },
    username: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    confirmed: {
      type: Boolean,
      default: false,
    },
  },
  { timestamps: true }
);

schema.method("hashPassword", function (): void {
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(this.password, salt);

  this.password = hash;
});

// User model
export const User = mongoose.model<IUser>("User", schema, "users");

【问题讨论】:

    标签: node.js typescript mongoose


    【解决方案1】:

    在定义方法时,schema 对象不知道它是 Schema 的 IUser 而不仅仅是任何 Document。创建时需要为Schema 设置泛型类型:new Schema&lt;IUser&gt;( ... )。

    【讨论】:

      【解决方案2】:

      你应该像这样声明一个扩展模型的接口:

          interface IUser {...}
          interface IUserInstanceCreation extends Model<IUser> {}
      

      然后声明你的架构;

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

      这也将确保 Schema 遵循 IUser 中的属性。

      【讨论】:

      • 我已经弄明白了,不过还是谢谢你
      【解决方案3】:

      正如一位猫鼬的合作者所建议的,我们可以使用以下方式来创建实例方法:

      const schema = new Schema<ITestModel, Model<ITestModel, {}, InstanceMethods>> // InstanceMethods would be the interface on which we would define the methods
      
      schema.methods.methodName = function() {}
      
      const Model = model<ITestModel, Model<ITestModel, {}, InstanceMethods>>("testModel", ModelSchema)
      
      const modelInstance = new Model();
      modelInstance.methodName() // works
      

      链接:https://github.com/Automattic/mongoose/issues/10358#issuecomment-861779692

      【讨论】:

        猜你喜欢
        • 2012-04-22
        • 2017-06-30
        • 2021-11-04
        • 2014-12-04
        • 2015-03-25
        • 2017-11-01
        • 2018-08-27
        • 2018-11-30
        相关资源
        最近更新 更多