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();
});
});
});
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) { ... }
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With