不明白为什么我在 Mongoose Pre save hook 上收到错误警告

Daf*_*fny 6 mongoose

我想使用预保存挂钩对我的密码进行哈希处理。我的密码得到了很好的哈希处理,但为什么我在预保存挂钩的“保存”方法名称上收到错误警告?

错误警告:没有重载与此调用匹配。最后一次超载出现以下错误。类型“save”的参数不可分配给类型“RegExp |”的参数 “插入许多”'.ts(2769)

这是代码:

UserSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }

  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});
Run Code Online (Sandbox Code Playgroud)

小智 0

您好,尝试为您的模型创建一个界面

interface IUser {
   email: string;
   password: string;       
}

const UserSchema = new mongoose.Schema<IUser>({
   email: {
        type: String,            
    },
    password: {
        type: String,
    },
});

// Encrypt password using bcrypt
UserSchema.pre("save", async function (next) {
    if (!this.isModified("password")) {
       next();
    }

   const salt = await bcrypt.genSalt(10);
   this.password = await bcrypt.hash(this.password, salt);
});

export default mongoose.model("User", UserSchema);
Run Code Online (Sandbox Code Playgroud)