-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方法,以比较EnteredPassword参数与数据库中的密码
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<any>'.
并且此错误出现在***突出显示的this.password的每个实例上
我以前在Javascript中使用过相同的方法,所以我不知道为什么它在打字稿上不起作用,以及如何将this.password绑定到Mongoose文档上
谢谢
看来@Mohammad已经帮助您bcrypt
实现了。我可以为您解决打字稿错误!
UserDoc
是一个打字稿界面,因此不应包含required
。它应该只描述UserDoc
对象的类型。默认情况下,属性是必需的。我们使用?:
它们是否是可选的,但看起来这里是所有必需的。
export interface UserDoc extends Document {
name: string;
email: string;
password: string;
dateJoined: string;
matchPassword: (pw: string) => Promise<boolean>
}
在创建时userSchema
,通过将构造函数的泛型变量设置为,可以告诉打字稿这是a的架构,UserDoc
而不仅仅是any的架构。Document
Schema
UserDoc
const userSchema = new Schema<UserDoc>({ ...
userSchema.methods.matchPassword
由于我们知道这this.password
是个错误,因此可以清除中的错误string
。我们也知道那enteredPassword
是string
因为我们matchPassword
在UserDoc
接口中为此方法定义了参数。
由于某种原因,该pre
方法无法自动识别我们的文档类型。但是该pre
方法本身是一个泛型函数,因此我们可以再次指定doc是一个UserDoc
。
userSchema.pre<UserDoc>( ...
这很愚蠢,但是我们在创建模型时必须再次指定泛型。
const User = mongoose.model<UserDoc>("User", userSchema);
现在User
具有type,mongoose.Model<UserDoc, {}>
并且您调用的所有方法都应该返回aUserDoc
而不是a Document
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句