Typescript mongoose 静态模型方法“属性在类型上不存在" [英] Typescript mongoose static model method "Property does not exist on type"

查看:17
本文介绍了Typescript mongoose 静态模型方法“属性在类型上不存在"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试向我的猫鼬模式添加一个静态方法,但我找不到它不能以这种方式工作的原因.

I am currently trying to add a static method to my mongoose schema but I can't find the reason why it doesn't work this way.

我的模型:

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] 属性 'hashPassword' 在类型 'Model' 上不存在.

If I now try to call User.hashPassword(password) I am getting the following error [ts] Property 'hashPassword' does not exist on type 'Model<IUserModel>'.

我知道我没有在任何地方定义方法,但我真的不知道我可以把它放在哪里,因为我不能把一个静态方法放到一个接口中.希望您能帮我找出错误,提前致谢!

I know that I didn't define the method anywhere but I don't really know where I could put it as I can't just put a static method into an interface. I hope you can help my find the error, thanks in advance!

推荐答案

我认为您遇到了我刚刚遇到的相同问题.这个问题在你的电话中.一些教程让您像这样从模型中调用 .comparePassword() 方法.

I think you are having the same issue that I just struggled with. This issue is in your call. Several tutorials have you call the .comparePassword() method from the model like this.

User.comparePassword(candidate, cb...)

这不起作用,因为该方法在 schema 上而不是在 model 上.我能够调用该方法的唯一方法是使用标准的 mongoose/mongo 查询方法找到模型的这个实例.

This doesn't work because the method is on the schema not on the model. The only way I was able to call the method was by finding this instance of the model using the standard mongoose/mongo query methods.

这是我的护照中间件的相关部分:

Here is relevant part of my passport middleware:

passport.use(
  new LocalStrategy({
    usernameField: 'email'
  },
    function (email: string, password: string, done: any) {
      User.findOne({ email: email }, function (err: Error, user: IUserModel) {
        if (err) throw err;
        if (!user) return done(null, false, { msg: 'unknown User' });
        user.schema.methods.comparePassword(password, user.password, function (error: Error, isMatch: boolean) {
          if (error) throw error;
          if (!isMatch) return done(null, false, { msg: 'Invalid password' });
          else {
            console.log('it was a match'); // lost my $HÏT when I saw it
            return done(null, user);
          }
        })
      })
    })
);

所以我使用 findOne({}) 来获取文档实例,然后不得不通过深入文档中的架构属性来访问架构方法 user.schema.methods.comparePassword

So I used findOne({}) to get the document instance and then had to access the schema methods by digging into the schema properties on the document user.schema.methods.comparePassword

我注意到的一些差异:

  1. 我的是一个 instance 方法,而你的是一个 static 方法.我相信有类似的方法访问策略.
  2. 我发现我必须将哈希值传递给 comparePassword() 函数.也许这对静态来说不是必需的,但我无法访问 this.password
  1. Mine is an instance method while yours is a static method. I'm confident that there is a similar method access strategy.
  2. I found that I had to pass the hash to the comparePassword() function. perhaps this isn't necessary on statics, but I was unable to access this.password

这篇关于Typescript mongoose 静态模型方法“属性在类型上不存在"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆