我尝试为用户模式创建方法hashPassword。
schema.method("hashPassword", function (): void {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(this.password, salt);
this.password = hash;
});
并得到密码错误Property 'password' does not exist on type 'Document<any>'.
这是我的档案
import mongoose, { Schema, Document } from "mongoose";
import bcrypt from "bcryptjs";
/**
* This interface should be the same as JWTPayload declared in types/global.d.ts file
*/
export interface IUser extends Document {
name: string;
email: string;
username: string;
password: string;
confirmed: boolean;
hashPassword: () => void;
checkPassword: (password: string) => boolean;
}
// User schema
const schema = new Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
confirmed: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
schema.method("hashPassword", function (): void {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(this.password, salt);
this.password = hash;
});
// User model
export const User = mongoose.model<IUser>("User", schema, "users");
5条答案
按热度按时间wd2eg0qa1#
在定义该方法时,
schema
对象并不知道它是IUser
的Schema
,而不是任何Document
。在创建Schema
时,需要为它设置泛型类型:new Schema<IUser>( ... )
.hec6srdp2#
正如mongoose的一位合作者所建议的,我们可以使用以下方法来创建示例方法:
链接:https://github.com/Automattic/mongoose/issues/10358#issuecomment-861779692
vi4fp9gy3#
您应该声明一个扩展Model的接口,如下所示:
然后声明模式;
这也将确保架构遵循IUser中的属性。
dy2hfwbg4#
这一点很清楚
whlutmcx5#
避免重新定义架构中已有类型的解决方案