【发布时间】:2021-05-09 04:24:39
【问题描述】:
-- 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"),
},
});
我创建了我的用户模型,我遇到的问题是创建 matchPassword 方法并使用 bcrypt 比较 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 中使用过同样的方法,所以我不知道为什么它在 typescript 上不起作用以及如何将 this.password 绑定到 Mongoose 文档
谢谢
【问题讨论】:
标签: node.js mongodb typescript mongoose bcrypt