TS2339:类型“Model<Document,{}>”上不存在属性“comparePassword”

Pra*_*mam 1 mongoose mongodb node.js typescript

我使用此代码定义了一个模式方法。当我在服务中使用时。它显示一个错误。

// 模型

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
}
Run Code Online (Sandbox Code Playgroud)

// 声明的方法

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

// 服务文件

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
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

这一行向我显示了错误。

const person = await User.comparePassword(password);

这是编辑器中的屏幕截图。

在此输入图像描述

这是终端截图

在此输入图像描述

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

Pra*_*mam 6

导出模型时出现错误。

export const User = mongoose.model<user>("User", userSchema);
Run Code Online (Sandbox Code Playgroud)

并在导出接口中添加声明该函数。

export const User = mongoose.model<user>("User", userSchema);
Run Code Online (Sandbox Code Playgroud)

函数是这样定义的。

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

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