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

时间:2019-08-09 18:08:56

标签: node.js mongodb typescript mongoose

我已经使用此代码定义了一种架构方法。虽然我在服务中使用。显示错误。

//型号

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

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

enter image description here

这是终端屏幕截图

enter image description here

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

2 个答案:

答案 0 :(得分:1)

您定义的Schema方法将适用于猫鼬实例,即您集合中的文档,而不适用于模型。另外,您直接尝试比较不应该的密码。您应该首先检查该用户是否存在,如果找到了该用户,则可以使用用户文档调用 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!!'
            });
        }
    }
}

希望这会有所帮助:)

答案 1 :(得分:0)

导出模型时出错。

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所说。该错误已得到纠正,实际错误正在导出模型。