Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – Typescript mongoose静态模型方法“属性不存在于类型上”大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在尝试为我的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,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;

IUSER:

export interface IUser {
    email: string;
    name: string;
    password: string;
}

如果我现在尝试调用User.hashPassword(密码),我收到以下错误[ts]属性’hashPassword’在类型’Model< IUserModel>‘上不存在.

我知道我没有在任何地方定义方法,但我真的不知道我可以把它放在哪里,因为我不能只是将静态方法放入接口.
我希望你能提前帮助我找到错误

解决方法

我认为你遇到的问题与我刚刚遇到的问题相同.这个问题在您的电话中.有几个教程可以像这样从模型中调用.comparePassword()方法.

User.comparePassword(candidate,cb...)

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

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

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,{ 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上的模式属性来访问模式方法.

我发现了几个不同之处:

> mine一个实例方法,而你的是静态方法.我相信有类似的方法访问策略.>我发现我必须将哈希传递给comparePassword()函数.也许这对静力学没有必要,但我无法访问this.password

大佬总结

以上是大佬教程为你收集整理的node.js – Typescript mongoose静态模型方法“属性不存在于类型上”全部内容,希望文章能够帮你解决node.js – Typescript mongoose静态模型方法“属性不存在于类型上”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: