javascript - 谁能帮我将代码转换为打字稿?
问题描述
我已经为模式实现了接口,但我不知道如何为猫鼬虚拟字段和方法定义类型
错误是:
'this' 隐含类型为 'any' 因为它没有类型 annotation.ts(2683)
'Document<any, any>'.ts(2339) 类型上不存在属性 'encryptPassword'
这是我的用户模型!
导入猫鼬,uuid 用于盐,crypto 用于加密。
import { model, Schema } from "mongoose";
import { v4 as uuid_v4 } from "uuid";
import crypto from "crypto";
定义 UserSchema 接口
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);
你能帮我把它转换成打字稿吗?
解决方案
推荐阅读
- grpc - gRPC 调用、通道、连接和 HTTP/2 生命周期
- python - 如何在没有逗号的情况下将多个值添加到字典中的单个键中?
- javascript - ASP.NET Core Razor 页面从 AJAX Post 下载文件
- python - Python - re.DOTALL 导致“无”输出
- dynamic - SQL Synapse,在 CREATE EXTERNAL TABLE 中使用动态/参数化 Azure 容器
- visual-studio-code - VSCode添加所有缺少的导入不起作用
- javascript - 根据用户选择显示价格
- swift - 在快照中捕获整个 tableview 单元格范围以进行打印和共享
- javascript - 在 Angular 中创建 javascript 对象时出错
- postgresql - brew postgresql-upgrade-database 的 initb 失败