【问题标题】:I am not getting the mongoose queried user as the returned value我没有得到猫鼬查询用户作为​​返回值
【发布时间】:2019-06-28 12:25:21
【问题描述】:

这是我的 apollo 解析器,我想返回用户,但它不返回任何内容,如果我返回查询本身,则无法进行密码检查

我的代码:

login: (parent, { email, password }, context, info) => {
          User.findOne({ email }, function(err, user) {
            if (user.length) {
              bcrypt.compare(password, user[0].password, function(err, res) {
                if (res) {
                  console.log(user[0]); // this has the user
                  return user[0]; // but this does not return anything
                } else {
                  throw new ApolloError("failed");
                }
              });
            } else {
              throw new ApolloError("failed");
            }
          });
    }

【问题讨论】:

  • 你试图从回调中返回一些东西到一个异步操作(实际上是两层深入到异步操作)。没有人关注返回值。
  • 我尝试了异步等待,但它也不起作用..你有什么建议?因为我认为我对验证逻辑没有任何选择
  • 如果可以使用这些 API 以使其返回 Promises,您可以使用 asyncawait,否则登录函数将需要调用自己的回调。
  • 我什至尝试在查询之外声明一个变量并用最终结果填充它,但它不起作用..有什么原因不起作用?
  • 对,这样的方法不可能奏效。它是异步的。对User.findOne() 的调用立即返回,并且在数据库操作完成之前不会调用其回调。

标签: javascript node.js mongoose react-apollo apollo-server


【解决方案1】:

我已经完成了这个解决方案,并且效果很好

login: async (parent, { email, password }, context, info) => {
      const user = await attemptSignIn(email, password);

      return user;
    }

const attemptSignIn = async (email, password) => {
  const message = "Incorrect email or password. Please try again.";

  const user = await User.findOne({ email });

  if (!user || !(await matchesPassword(user, password))) {
    throw new AuthenticationError(message);
  }

  return user;
};

matchesPassword = (user, password) => {
  return compare(password, user.password);
};

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2019-09-29
    • 1970-01-01
    • 2020-09-26
    • 2018-05-26
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2018-07-12
    相关资源
    最近更新 更多