【问题标题】:TS2339: Property 'comparePassword' does not exist on type 'Model<Document, {}>'TS2339:“模型<Document,{}>”类型上不存在属性“comparePassword”
【发布时间】:2019-12-17 12:00:40
【问题描述】:

我已经使用这段代码定义了一个模式方法。虽然我在服务中使用。它显示错误。

// 型号

export interface User extends mongoose.Document {
    name: {
        type: String,
        required: [true, 'Please tell us your name.']
    },
    username: {
        type: String,
        required: [true, 'Please select a username.']
    },
    email: {
        type: String,
        required: [true, 'Please provide us your email.'],
        lowercase: true,
        unique: true,
        validate: [validator.isEmail, 'Please provide us your email.']
    },
    password: {
        type: String,
        required: [true, 'Please select a password.'],
        minLength: 8
        select: false
    },
    passwordConfirmation: {
        type: String,
        required: [true, 'Please re-enter your password.'],
        minLength: 8,
    },
    comparePassword(password: string): boolean
}

// 方法声明

userSchema.method('comparePassword', function (password: string): boolean {
    if (bcrypt.compareSync(password, this.password)) {
        return true;
    } else {
        return false;
    }
});

//服务文件

public loginUser  = async(req: Request, res: Response, next) => {
        const {username, password} = req.body;
        if(!username || !password){
            res.status(400).json({
                status: 'failed',
                message: 'Please provide username and password.'
            });
            return next(new AppError('Please provide username and password.', 400));
        } else {
            const person = await [![User][1]][1].comparePassword(password);
            const token = signToken(person._id);
            res.status(200).json({
                status: 'success',
                accessToken : token
            });
        }
    }

这一行显示了错误。

const person = await User.comparePassword(password);

这是编辑器中的截图。

这是终端截图

我能知道这里有什么问题吗?我尝试查看解决方案,但找不到。

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    导出模型时出错。

    export const User = mongoose.model<user>("User", userSchema);
    

    并在导出界面中添加声明函数。

    export interface user extends mongoose.Document {
        name: String,
        username: String,
        email: String,
        password: String,
        passwordConfirmation: String,
        comparePassword(candidatePassword: string): Promise<boolean>;
    }
    

    而函数是这样定义的。

    userSchema.methods.comparePassword = function (candidatePassword: string): Promise<boolean> {
        let password = this.password;
        return new Promise((resolve, reject) => {
            bcrypt.compare(candidatePassword, password, (err, success) => {
                if (err) return reject(err);
                return resolve(success);
            });
        });
    };
    

    然后调用函数person.comparePassword()出现错误。它应该在找到现有用户后调用。正如@Mohammed Amir Ansari 所说。错误已得到纠正,实际错误是导出模型。

    【讨论】:

      【解决方案2】:

      您定义的 Schema 方法将可用于 mongoose 实例,即您的集合中的文档,而不是模型。此外,您正在直接尝试比较不应该出现的密码。您应该首先检查用户是否存在,如果用户找到,您可以使用用户文档调用您的 comparePassword(),相同的代码将是:

      public loginUser = async (req: Request, res: Response, next) => {
          const {
              username,
              password
          } = req.body;
          if (!username || !password) {
              res.status(400).json({
                  status: 'failed',
                  message: 'Please provide username and password.'
              });
              return next(new AppError('Please provide username and password.', 400));
          } else {
              const person = await User.findOne({
                  username
              });
              if (!person) {
                  return res.status(404).json({
                      message: 'No User Found.'
                  });
              }
              const isValidPassword = await person.comparePassword(password);
              if (isValidPassword) {
                  const token = signToken(person._id);
                  return res.status(200).json({
                      status: 'success',
                      accessToken: token
                  });
              } else {
                  return res.status(400).json({
                      status: 'fail',
                      message: 'Invalid Password!!'
                  });
              }
          }
      }
      

      希望这会有所帮助:)

      【讨论】:

      • 是的,在编写找到现有用户然后调用函数的代码之后。它仍然显示相同的错误。我添加了显示错误的编辑器和终端的屏幕截图。你能调查一下吗?谢谢。
      • 很抱歉没有指定导出语句。有效。谢谢
      • 很高兴它有帮助...快乐编码:)
      猜你喜欢
      • 2016-03-14
      • 2017-02-25
      • 2021-11-24
      • 2019-01-11
      • 2021-05-08
      • 2021-10-15
      • 2020-12-13
      • 2021-08-04
      • 2020-07-01
      相关资源
      最近更新 更多