node.js - 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 和一个空对象。
感谢您的回答。我找到了缺失的地方。我将散列密码存储在数据库中,但我忘记搜索散列密码
解决方案
首先,您应该考虑不要将密码作为明文存储在数据库中以及在查找用户查询密码时。我建议使用像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)
}
})
推荐阅读
- node.js - 执行模型单元测试文件时数据库认证中的回调导致错误
- xslt - 如何将 xml 的一部分转换为没有命名空间的新 xml?
- python - PNG文件无法打开
- ubuntu - 无法安装 Ros Melodic,为什么?
- php - 无法使用 php 解码 arduino 编码的 AES-128 ECB 字符串
- python - 如何编写一个可以按位置访问节点的树类?
- arrays - [MongoDB]如何从数组中查找对象?
- c# - ASP .NET Core 中的 CORS 问题 - 响应中的“Access-Control-Allow-Origin”标头的值不能是通配符 '*
- javascript - 如何使用外部作用域中的同名变量解构 Typescript 中的变量?
- android - Android - 用于重复元素的结构化布局 - 游戏