如何解决猫鼬验证失败

时间:2020-09-11 22:00:46

标签: node.js mongoose

嘿,这对您的nodejs众神来说应该非常简单,我正在尝试使用mongoose使用nodejs进行身份验证系统,以便服务器成功接收前端中输入的电子邮件和参数,但是好像我的某个地方我的逻辑是我做得不好,请您提供一些帮助来处理此错误,因为在后端登录控制台时会发生以下情况。

User Successfully Found
EMAIL:  test1@gmail.com
PASSWORD:  test1
SIGNINUSER: undefined

即使输入了错误的用户,我也会找到用户成功

**有趣的是,当我删除。然后时,我取回了用户对象,但返回有关未处理的承诺

的错误

下面我用来处理用户登录的代码

router.post("/signin", async (request, response) => {
  const signinUser = await User.find({
    email: request.body.email,
    password: request.body.password,
  })
    .then((response) => {
      console.log("User Successfully Found");
    })
    .catch((error) => {
      console.log("User Does not exist");
    });
  
  //Here I was trying to check if I really am receiving the data from the client
  //Just to find that I am receiving the clients data
  console.log("EMAIL: ", request.body.email);
  console.log("PASSWORD: ", request.body.password);

  //Here I was trying to check if the usersInfo is being set inside the siginUser variable 
  //just to find that I getting the value of undefined
  console.log("SIGNINUSER: ", signinUser);

  if (signinUser) {
    response.status(200).json({
      _id: signinUser.id,
      name: signinUser.name,
      email: signinUser.email,
      isAdmin: signinUser.isAdmin,
      token: getToken(user),
    });
  } else {
    response.status(401).send({ message: "Invalid Email or Password" });
  }
});

1 个答案:

答案 0 :(得分:0)

如果不运行代码,我会说您正在将“ await”与“ then”和“ monoogose”查询混合在一起。因此,在提出的解决方案中,User.find()返回查询(这不是一个承诺,而是一个必要的),您可以执行该查询以获取一个承诺并等待结果。删除然后保留代码行为可能看起来像这样。

router.post("/signin", async (request, response) => {
    const signinUser = await User.find({
        email: request.body.email,
        password: request.body.password,
    }).exec();
    if (!signinUser) {
        console.log("User Does not exist");
        return response.status(401).send({ message: "Invalid Email or Password" });
    }
    console.log("User Successfully Found");
    console.log("EMAIL: ", request.body.email);
    console.log("PASSWORD: ", request.body.password);
    console.log("SIGNINUSER: ", signinUser);
    return response.status(200).json({
        _id: signinUser.id,
        name: signinUser.name,
        email: signinUser.email,
        isAdmin: signinUser.isAdm
        token: getToken(user),
    });
});

我希望这会有所帮助。

更多信息here Mongoose - What does the exec function do?