Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 679
Barometer Avatar asked Dec 06 '18 04:12

Barometer


2 Answers

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) { ... }
like image 101
Shivam Pandey Avatar answered Sep 28 '22 22:09

Shivam Pandey


you can also pass the interface type to the schema itself.

import { model, Schema, Document } from 'mongoose';

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

interface IUser extends Document{
  email: string;
  password: string;
  name: string;
}
like image 20
samehanwar Avatar answered Sep 28 '22 21:09

samehanwar