node.jstypescriptmongoosebcrypt

Property "password" does not exists on type Document


I am getting this error Property "password" does not exists on type Document. So can anyone tell if there is something wrong with my code ?

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();
    });
  });
});

enter image description here


Solution

  • You need to add type here with pre-save hook as per the mongoose docs, pre hook is defined as,

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

    and if you have an interface like below then,

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

    Add type with pre-save hook,

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