typescript - 文档类型上不存在属性“密码”
问题描述
我收到此错误 文档类型上不存在属性“密码”。那么任何人都可以判断我的代码是否有问题?
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();
});
});
});
解决方案
您需要根据猫鼬文档在此处使用预保存挂钩添加类型,预挂钩定义为,
/**
* 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) { ... }
推荐阅读
- javascript - 如何使用Javascript / Jquery检测水平滚动的底部视口滚动条
- mysql - SpringBoot Cloud Foundry 覆盖数据库池大小 - 通信链路故障
- c++ - 从特定代码部分跳转到函数开始
- blockchain - Msg.sender 在“视图”函数中不起作用,为什么?有解决方法吗?
- php - 无法使用 PHP 附加文本文件
- java - Kotlin Jar 被 Java 应用程序调用 [kotlin/jvm/internal/Intrinsics]
- swift - Swift 3 在地图或过滤器中使用可选链接
- javascript - 尝试使用转义和非转义分隔符拆分字符串
- python - PyInstaller 应用程序未在 Mac 上打开
- ios - 如何从带有 JSON 数据的字符串中获取 UIImage