【发布时间】:2017-07-15 20:38:25
【问题描述】:
我目前正在尝试向我的 mongoose 架构添加一个静态方法,但我找不到它不能以这种方式工作的原因。
我的模特:
import * as bcrypt from 'bcryptjs';
import { Document, Schema, Model, model } from 'mongoose';
import { IUser } from '../interfaces/IUser';
export interface IUserModel extends IUser, Document {
comparePassword(password: string): boolean;
}
export const userSchema: Schema = new Schema({
email: { type: String, index: { unique: true }, required: true },
name: { type: String, index: { unique: true }, required: true },
password: { type: String, required: true }
});
userSchema.method('comparePassword', function (password: string): boolean {
if (bcrypt.compareSync(password, this.password)) return true;
return false;
});
userSchema.static('hashPassword', (password: string): string => {
return bcrypt.hashSync(password);
});
export const User: Model<IUserModel> = model<IUserModel>('User', userSchema);
export default User;
用户:
export interface IUser {
email: string;
name: string;
password: string;
}
如果我现在尝试调用User.hashPassword(password),我会收到以下错误[ts] Property 'hashPassword' does not exist on type 'Model<IUserModel>'.
我知道我没有在任何地方定义方法,但我真的不知道我可以把它放在哪里,因为我不能只将静态方法放入接口中。 希望您能帮我找出错误,在此先感谢!
【问题讨论】:
标签: node.js typescript mongoose