【发布时间】:2021-05-04 12:47:56
【问题描述】:
我正在使用 TypeScript 在 Mongoose 中创建用户模式,当我提到模式的属性时,例如 this.password,我收到以下错误: “文档”类型上不存在属性“密码” 当我使用 pre() 函数的属性时,不会发生此错误,因为我可以使用 IUser 界面键入它。我不能对我的方法做同样的事情,那么有什么办法可以解决这个问题吗?这很奇怪,因为我发现其他人使用相同的代码并且它适用于他们,所以错误可能来自另一件事。在这里您可以找到错误的存储库:https://github.com/FaztWeb/restapi-jwt-ts
import { model, Schema, Document } from "mongoose";
import bcrypt from "bcrypt";
export interface IUser extends Document {
email: string;
password: string;
comparePassword: (password: string) => Promise<Boolean>
};
const userSchema = new Schema({
email: {
type: String,
unique: true,
required: true,
lowercase: true,
trim: true
},
password: {
type: String,
required: true
}
});
userSchema.pre<IUser>("save", async function(next) {
const user = this;
if (!user.isModified("password")) return next();
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
next();
});
userSchema.methods.comparePassword = async function(password: string): Promise<Boolean> {
return await bcrypt.compare(password, this.password);
};
export default model<IUser>("User", userSchema);
【问题讨论】:
标签: typescript mongoose model properties document