typescript - “文档”类型上不存在属性“密码”'
问题描述
我正在使用 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);
解决方案
您可以在首次创建的位置添加通用声明Schema
:
const userSchema = new Schema<IUser>({ ... });
这应该使它在您添加方法时this
被精炼以包含在内。IUser
推荐阅读
- python - filterAcceptsRow() 究竟做了什么?
- linux - 主管超限
- node.js - 如何同时使用 babel 来运行带有 React 前端的 Node 服务器?
- angular - 导入时在“@angular/http”处显示错误
- python - 如何获取语料库中单词的平均 TF-IDF 值?
- c# - 如何在多个线程上对收到的 udp 数据包进行负载平衡?
- sql-server - 如何加入表
- mysql - 如何在多对多关系mysql中显示记录?
- algorithm - 在解决约束问题时,有没有比完全排列更好的 Multiple 算法?
- ios - Cordova 提交到应用商店时出现“Apple 将停止接受使用 UIWebView 的应用提交”警告