简体   繁体   English

无法访问 object 属性

[英]can't get access to an object property

I'm using JWT token compare function to the user password in order to authenticate user login but after the mongoose query I cant get access to the user password我正在使用 JWT 令牌将 function 与用户密码进行比较以验证用户登录,但是在 mongoose 查询之后我无法访问用户密码

exports.login = async(req, res, next) => {
    
        const {email, password} = req.body

//checking if email and password exists
        if(!email || !password){
            return next(new AppError('Provide email and password', 400))
        } 

//checking if the user exists and password is correct
    try {   
        const user = await User.find({email}).select('+password')
        if(!user || !(await user.correctPassword(password, user.password))){
            return next(new AppError('Incorrect email and password', 401))
        }
//when everything is ok send the response to the client
        const token = SignToken(user._id)
        console.log(token);
        res.status(200)
            .json({
            status: 'success',
            token
            })
        } catch(err) {
            res.status(400).json({
                status: 'fail',
                message: err
            })
        }


}

After viewing the user.password in the console it is showing undefined so my compare function is not working.在控制台中查看user.password后,它显示undefined ,因此我的compare function 不起作用。 I'm fairly new to JWT我是 JWT 的新手

Your password is undefined as you made mistake while projecting fields by User.find({email}).select('+password') .In the mongoose the select method, you can't pass "+" .您的密码undefined ,因为您在通过User.find({email}).select('+password')投影字段时出错。在 mongoose select 方法中,您不能传递"+" But if you want to skip any property you can use the "-" operator select('-password) .但是如果您想跳过任何属性,您可以使用"-"运算符select('-password) And Also, you can't write like select("-username password") .而且,你不能像select("-username password")这样写。 Only the property name of the collection 'password' is enough in the select("password") method to find the password.select("password")方法中,仅集合'password'的属性名称就足以找到密码。

Look that answer might be helpful for you.看看这个答案可能对你有帮助。

answer回答

Documentation Here 文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM