Javascript 有人能帮我把代码转换成打字脚本吗?
我已经为模式实现了接口,但我不知道如何为mongoose虚拟字段和方法定义类型 错误包括: “this”隐式具有类型“any”,因为它没有类型批注。ts(2683) 类型“Document”上不存在属性“encryptPassword”。ts(2339)` 这是我的用户模型 导入猫鼬,uuid用于salt,crypto用于加密Javascript 有人能帮我把代码转换成打字脚本吗?,javascript,node.js,typescript,mongoose,mongoose-schema,Javascript,Node.js,Typescript,Mongoose,Mongoose Schema,我已经为模式实现了接口,但我不知道如何为mongoose虚拟字段和方法定义类型 错误包括: “this”隐式具有类型“any”,因为它没有类型批注。ts(2683) 类型“Document”上不存在属性“encryptPassword”。ts(2339)` 这是我的用户模型 导入猫鼬,uuid用于salt,crypto用于加密 import { model, Schema } from "mongoose"; import { v4 as uuid_v4 } from &qu
import { model, Schema } from "mongoose";
import { v4 as uuid_v4 } from "uuid";
import crypto from "crypto";
定义用户模式接口
export interface UserSchema extends Document {
_id: string;
username: string;
email: string;
hashed_password: string;
salt: string;
photo: {
data: Buffer;
contentType: string;
};
about: string;
}
定义模式
const userSchema: Schema = new Schema(
{
username: {
type: String,
trim: true,
required: true,
},
email: {
type: String,
trim: true,
required: true,
},
hashed_password: {
type: String,
require: true,
},
salt: {
type: String,
},
photo: {
data: Buffer,
contentType: String,
},
about: {
type: String,
trim: true,
},
},
{ timestamps: true }
);
mongoose虚拟场和方法
userSchema
.virtual("password")
.set(function (password) {
//create temporary variable called _password
this._password = password;
//generate a timestamp
this.salt = uuid_v4();
//encryptPassword()
this.hashed_password = this.encryptPassword(password);
})
.get(function () {
return this._password;
});
//methods
userSchema.methods = {
authenticate: function (plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
},
encryptPassword: function (password) {
if (!password) return "";
try {
return crypto
.createHmac("sha1", this.salt)
.update(password)
.digest("hex");
} catch (err) {
return "";
}
},
};
export default model<UserSchema>("User", userSchema);
userSchema
.virtual(“密码”)
.set(功能(密码){
//创建名为_password的临时变量
此密码为.\u password=password;
//生成时间戳
this.salt=uuid_v4();
//加密密码()
this.hashed_password=this.encryptPassword(密码);
})
.get(函数(){
返回此密码。\u;
});
//方法
userSchema.methods={
身份验证:函数(纯文本){
返回此.encryptPassword(明文)==此.hashed_密码;
},
encryptPassword:函数(密码){
如果(!password)返回“”;
试一试{
返回密码
.createHmac(“sha1”,这是盐)
.更新(密码)
.摘要(“十六进制”);
}捕捉(错误){
返回“”;
}
},
};
导出默认模型(“用户”,userSchema);
你能帮我把它转换成打字脚本吗