检查MySQL中的价值存在

发布于 2025-02-13 02:44:00 字数 584 浏览 1 评论 0原文

我正在开发具有ExpressJS的用户身份验证系统。因此,要存储用户数据,我使用MySQL数据库...当我查询数据库时,我会这样做:从用户中选择密码,其中emair = email here

问题是,如果电子邮件不存在,我不知道返回错误消息的优雅解决方案。有点可以理解吗?

可以得出结论:我想知道当我查询数据库时是否存在该值,这样我就不会收到错误消息。

编辑:

  const query = `SELECT password FROM USERS WHERE email=?;`;
  let [rows, fields] = await db.promise().query(query, [req.body.email]);

  const password = rows[0].password;
  console.log(password);

这给了我错误:无法读取未定义的读取“密码”的属性。

因此,它正在尝试访问.Password列。我可以防止吗?

预先感谢!祝您有美好的一天

I am developing a user authentication system with expressjs. Therefore to store user data i use a mysql database... When I query to my database I do it with this: SELECT password FROM USERS WHERE email=EmailHere
The problem with this is I dont know an elegant solution to returning an error message if the email doesnt exist. Somewhat understandable?

So to conclude: I want to know if that value exists when I query to the db so I dont get an error message.

Edit:

  const query = `SELECT password FROM USERS WHERE email=?;`;
  let [rows, fields] = await db.promise().query(query, [req.body.email]);

  const password = rows[0].password;
  console.log(password);

This gives me the error: Cannot read properties of undefined reading 'password'.

So it is trying to access the .password column. Can I prevent that?

Thanks in advance! Have a great day

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

林空鹿饮溪 2025-02-20 02:44:00

好的,事实证明:

如果我检查行阵列的长度是否长度; 0它解决了问题。在Else语句中,我只需记录一个错误消息即可说该用户不存在。这看起来像这样:

if (!rows.length > 0) return res.status(400).send('User doensnt exist!');
const password = rows[0].password;
// Declaring the variable after I know it exists.

感谢@danblack的答案!

Ok it turns out:

If I check if the length of the rows Array > 0 it fixes the problem. In the else statement I can just log out an error message to say the user does not exist. This could look something like this:

if (!rows.length > 0) return res.status(400).send('User doensnt exist!');
const password = rows[0].password;
// Declaring the variable after I know it exists.

Thanks to @danblack for this answer!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文