首页 > 解决方案 > 文档类型上不存在属性“密码”

问题描述

我收到此错误 文档类型上不存在属性“密码”。那么任何人都可以判断我的代码是否有问题?

const userSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: { type: String, required: true }
});

userSchema.pre("save", function save(next) {
  const user = this;
  if (!user.isModified("password")) {
    return next();
  }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, (err: mongoose.Error, hash) => {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    });
  });
});

在此处输入图像描述

标签: typescriptmongoosebcrypt

解决方案


您需要根据猫鼬文档在此处使用预保存挂钩添加类型,预挂钩定义为,

/**
 * Defines a pre hook for the document.
 */
pre<T extends Document = Document>(
  method: "init" | "validate" | "save" | "remove",
  fn: HookSyncCallback<T>,
  errorCb?: HookErrorCallback
): this;

如果你有一个像下面这样的界面,

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

添加带有预保存钩子的类型,

userSchema.pre<IUser>("save", function save(next) { ... }

推荐阅读