Typescript mongoose static model method “Property does not exist on type”

后端 未结 5 964
囚心锁ツ
囚心锁ツ 2020-12-12 17:58

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.

My model:

import * as          


        
5条回答
  •  天涯浪人
    2020-12-12 18:58

    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...)
    

    This doesn't work because the method is 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);
              }
            })
          })
        })
    );
    

    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

    A couple of differences that I noticed:

    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

提交回复
热议问题