首页 > 解决方案 > User.findOne 返回 null

问题描述

router.post("/login", async (req, res) => 
{
        try
        {
            console.log(req.body.email)
            const user = await User.findOne({email: req.body.email, password: req.body.password})
            if(user)
            {
                return res.redirect("/")
            }
            console.log(user)
            res.status(200).send(user)
        }
        catch(e)
        {
            res.status(400).send(e)
        }
})

我正在尝试在 MongoDB 中查找用户,但用户变量返回null并且我得到状态代码 200 和一个空对象。

感谢您的回答。我找到了缺失的地方。我将散列密码存储在数据库中,但我忘记搜索散列密码

标签: node.jsmongodbexpressmongoose

解决方案


首先,您应该考虑不要将密码作为明文存储在数据库中以及在查找用户查询密码时。我建议使用像bcrypt这样的散列算法来验证它们。

关于您的问题,您必须知道 mongoose在找不到条目时不会抛出错误,并且您只会在抛出错误时发送 404。我建议您将代码更改为以下内容:

router.post("/login", async (req, res) => 
{
        try
        {
            console.log(req.body.email)
            const user = await User.findOne({email: req.body.email})

            if (user) {
                // TODO: Use hashing algorithm to verify password
                console.log(user)
                res.status(200).send(user)
                return res.redirect("/")
            } else {
                res.status(400).send("User not found")
            }
            
        }
        catch(e)
        {
            res.status(500).send("Server error: " + e.message)
        }
})

推荐阅读