作者:手机用户2502870941 | 来源:互联网 | 2023-10-10 11:56
-- userSchema.ts 接口
import mongoose, { Schema, Document } from "mongoose";
import moment from "moment";
import bcrypt from "bcrypt";
export interface UserDoc extends Document {
name: {
type: string;
required: boolean;
};
email: {
type: string;
required: boolean;
};
password: {
type: string;
required: boolean;
};
dateJoined: {
type: string;
default: string;
};
}
const userSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
dateJoined: {
type: String,
default: moment().format("MMMM Do YYYY"),
},
});
我创建了我的用户模型,我遇到的问题是使用 bcrypt创建matchPassword方法来比较enterPassword参数与数据库中的密码
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password); ***
};
userSchema.pre("save", async function (next) {
if (this.isModified("password")) {
next();
}
const salt = bcrypt.genSalt(10);
*** this.password = await bcrypt.hash(this.password, await salt); ***
});
const User = mongoose.model("User", userSchema);
错误信息如下:
Property 'password' does not exist on type 'Document'.
并且此错误出现在this.password 的每个实例上,以 *** 突出显示
我之前在 Javascript 中使用过相同的方法,所以我不知道为什么它在打字稿上不起作用,以及如何将this.password绑定到 Mongoose 文档
谢谢
回答
看起来@Mohammad 已经帮助你bcrypt
实现了。我可以帮你解决打字稿错误!
UserDoc
是一个打字稿接口,所以它不应该有像required
. 它应该只描述UserDoc
对象的类型。默认情况下需要属性。我们使用?:
if 它们是可选的,但看起来这里都是必需的。
export interface UserDoc extends Document {
name: string;
email: string;
password: string;
dateJoined: string;
matchPassword: (pw: string) => Promise
}
当您创建userSchema
,你告诉打字稿,这是一个模式UserDoc
-不是随便什么Document
-通过设定的通用变量Schema
构造函数UserDoc
。
const userSchema = new Schema({ ...
这清除了错误,userSchema.methods.matchPassword
因为我们知道这this.password
是一个string
. 我们也知道这enteredPassword
是string
因为我们matchPassword
在UserDoc
接口中定义了这个方法的参数。
出于某种原因,该pre
方法不会自动知道我们的文档类型。但是该pre
方法本身是一个通用函数,因此我们可以再次指定我们的 doc 是一个UserDoc
.
userSchema.pre( ...
这很愚蠢,但我们必须在创建模型时再次指定泛型。
const User = mongoose.model("User", userSchema);
现在User
有类型mongoose.Model
,你调用的任何方法都应该返回 aUserDoc
而不仅仅是 a Document
。