You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中基于MongoDB筛选借方或贷方交易

解决方案

你的现有代码问题在于只筛选了返回字段,但没有过滤掉非目标类型的交易——比如查贷方交易时,会把那些credit为0的借方交易也返回。结合你保存交易时的逻辑(借方交易设credit=0,贷方交易设debit=0),只需在查询条件里加上对应字段大于0的过滤规则,就能得到纯借方/贷方的交易列表。

1. 修复查询逻辑

直接修改两个接口的find查询条件,添加字段过滤:

贷方交易接口优化

router.get("/get-credit-transaction/:email", async (req, res) => {
  try {
    // 鉴权逻辑不变
    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith("Bearer ") ||
      !req.headers.authorization.split(" ")[1]
    ) {
      return res.status(422).json({ message: "Please Provide Token!" });
    }
    // 添加credit > 0的过滤条件,只返回真正的贷方交易
    const trans = await Transaction.find(
      { email: req.params.email, credit: { $gt: 0 } },
      { email: 1, narration: 1, credit: 1, amount: 1 }
    );
    res.status(200).json(trans);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});

借方交易接口优化

router.get("/get-debit-transaction/:email", async (req, res) => {
  try {
    // 鉴权逻辑不变
    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith("Bearer ") ||
      !req.headers.authorization.split(" ")[1]
    ) {
      return res.status(422).json({ message: "Please Provide Token!" });
    }
    // 添加debit > 0的过滤条件,只返回真正的借方交易
    const trans = await Transaction.find(
      { email: req.params.email, debit: { $gt: 0 } },
      { email: 1, narration: 1, debit: 1, amount: 1 }
    );
    res.status(200).json(trans);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});

2. 优化代码冗余(可选)

两个接口的鉴权逻辑完全重复,可以抽成中间件复用,减少代码冗余:

// 定义鉴权中间件
const authMiddleware = (req, res, next) => {
  if (
    !req.headers.authorization ||
    !req.headers.authorization.startsWith("Bearer ") ||
    !req.headers.authorization.split(" ")[1]
  ) {
    return res.status(422).json({ message: "Please Provide Token!" });
  }
  next();
};

// 使用中间件简化接口
router.get("/get-credit-transaction/:email", authMiddleware, async (req, res) => {
  try {
    const trans = await Transaction.find(
      { email: req.params.email, credit: { $gt: 0 } },
      { email: 1, narration: 1, credit: 1, amount: 1 }
    );
    res.status(200).json(trans);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});

router.get("/get-debit-transaction/:email", authMiddleware, async (req, res) => {
  try {
    const trans = await Transaction.find(
      { email: req.params.email, debit: { $gt: 0 } },
      { email: 1, narration: 1, debit: 1, amount: 1 }
    );
    res.status(200).json(trans);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});

逻辑说明

  • MongoDB的$gt操作符用于匹配字段值大于指定值的文档,这里用credit: { $gt: 0 }过滤出真正的贷方交易(排除那些credit为0的借方交易),借方同理。
  • 字段选择里用1代替true是MongoDB的标准写法,两者效果完全一致。

内容的提问来源于stack exchange,提问作者Pamela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:07:49