猫鼬NodeJS-条件检查问题

时间:2019-07-19 15:52:07

标签: javascript node.js mongodb rest express

一个简单的问题。

尝试重构此代码并将其拆分为不同的功能

router.put("/sendAmount/:id", function(req, res) {
  User.findOne({ accountId: req.params.id }, { amount: 1, _id: 0 }, function(
    err,
    account
  ) {
    if (err) return res.status(500).send("Cannot find initial account");
    const accountAmount = JSON.parse(account.amount);
    const targetAmount = req.body.amount;
    if (accountAmount < targetAmount) {
      return res.status(500).send("Not enough funds on the account. Aborted");
    } else {
      User.findOneAndUpdate(
        { accountId: req.body.accountId },
        { $inc: { amount: req.body.amount } },
        function(err, account) {
          if (!account) {
            return res.status(500).send("Target account not found");
          } else {
            User.findOneAndUpdate(
              { accountId: req.params.id },
              { $inc: { amount: -req.body.amount } },
              function(err, account) {
                if (err)
                  return res.status(500).send("Something went really wrong");
                return res.status(200).send("Everything went fine");
              }
            );
          }
        }
      );
    }
  });
});

我尝试将第一个User.findOne拆分为一个不同的函数,该函数将返回true或false,并在此之后继续执行或仅返回错误代码消息。

我尝试过的是:

const checkInitialAccountAmount = function(req) {
  User.findOne({ accountId: req.params.id }, { amount: 1, _id: 0 }, function(
    err,
    account
  ) {
    if (err) return res.status(500).send("Cannot find initial account");
    const accountAmount = JSON.parse(account.amount);
    const targetAmount = req.body.amount;
    console.log(accountAmount > targetAmount);
    return accountAmount > targetAmount;
  });
};

router.put("/sendAmount/:id", function(req, res) {
  checkInitialAccountAmount(req.params.id, req, res);
  if (checkInitialAccountAmount(req.params.id, req, res) === false) {
    console.log("This is false");
  } else {
    console.log("This is true");
  }
  User.findOneAndUpdate(
    { accountId: req.body.accountId },
    { $inc: { amount: req.body.amount } },
    function(err, account) {
      if (!account) {
        return res.status(500).send("Target account not found");
      } else {
        User.findOneAndUpdate(
          { accountId: req.params.id },
          { $inc: { amount: -req.body.amount } },
          function(err, account) {
            if (err) return res.status(500).send("Something went really wrong");
            return res.status(200).send("Everything went fine");
          }
        );
      }
    }
  );
});

但是,由于某种奇怪的原因,它既不发送“ true”也不发送“ false”,并且无论如何都会执行该代码。我究竟做错了什么?

0 个答案:

没有答案