【问题标题】:How to check whether a user exists in mongoose?如何检查用户是否存在于猫鼬中?
【发布时间】:2021-12-01 16:02:11
【问题描述】:

所以,我正在尝试检查是否有用户我有以下代码:

const userExist = await User.find({ username: req.body.username });
if (userExist)
   return res.status(400).send({ message: "User already exists" });

但即使用户不存在,它仍然会给出错误User already exists 并且 userExists 对象返回 []

【问题讨论】:

  • 使用User.findOne 而不是User.find
  • @Shahab 确保使用 findOnefind 方法遍历 整个数据库 以找到尽可能多的记录,而 findOne 则在找到第一个匹配项后立即停止。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

你可以使用const user = await User.findOne({ username: req.body.username }); 这只有一个,你可以检查!用户

【讨论】:

    【解决方案2】:

    原因是[]Javascript 中为真。您需要检查长度并检查数组中是否有一些数据。

    const userExist = await User.find({ username: req.body.username });
    if (userExist.length > 0)
         return res.status(400).send({ message: "User already exists" });
    

    供以后参考,以下所有值在JS中都是真实的。

    if (true)
    if ({})
    if ([])
    if (42)
    if ("0")
    if ("false")
    if (new Date())
    if (-42)
    if (12n)
    if (3.14)
    if (-3.14)
    if (Infinity)
    if (-Infinity)
    

    注意:建议您查看this链接。

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      相关资源
      最近更新 更多