首页 > 解决方案 > 尽管我正在对其进行变异,但对象返回相同

问题描述

即将到来的代码片段将从用户 JSON 对象中删除密码属性并返回它作为响应。发生的事情是密码属性仍在返回!


const signin = (req, res, next) => {
    let requestBody = req.body;

    userModel.findUserByEmail(requestBody.email).then(user => {
        bcrypt.compare(requestBody.password, user.password, (error, result) => {
            if (!result) {
                return res.status(500).json({
                    status: false,
                    message: 'Auth Failed!',
                    error
                });
            }

            if (error) {
                return res.status(500).json({
                    error
                });
            }

            let token = jwt.sign({
                email: user.email,
                userId: user._id
            }, 
            process.env.JWT_KEY, 
            {
                expiresIn: "2h"
            });

            // remonve password key
            delete user.password

            res.status(200).json({
                status: true,
                message: 'Authenticated!',
                data: {
                    token,
                    user
                }
            });
        });

    }).catch(error => {
        return res.status(500).json({
                status: false,
                message: 'Auth Failed!',
                error
            });
    });
}

不确定问题是否与异步编译有关

标签: javascriptnode.jsjson

解决方案


您可以在没有密码的情况下创建一个新对象并在您的响应中使用它:

const { password, ...restOfUser } = user

res.status(200).json({
  status: true,
  message: 'Authenticated!',
  data: {
    token
    user: restOfUser
  }
})

推荐阅读