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

在Node.js的MongoDB中组合使用$pull、$slice和$inc实现数据更新

MongoDB文档处理:交易删除、数组截取与图表数据更新

现有文档结构

[
  {
    "_id": "64a5a6fb80a26800e9b7d885",
    "userId": "123456789",
    "transactions": [
      {
        "title": "title_1",
        "price": 40,
        "_id": "64a5bcbc4c28d90fdfc5c067"
      },
      {
        "title": "title_2",
        "price": 40,
        "_id": "64a5bcbc4c28d90fdfc5c068"
      },
      {
        "title": "title_3",
        "price": 40,
        "_id": "64a5bcbc4c28d90fdfc5c064"
      },
      {
        "title": "title_4",
        "price": 40,
        "_id": "64a5bcbc4c28d90fdfc5c061"
      },
      {
        "title": "title_5",
        "price": 40,
        "_id": "64a5bcbc4c28d90fdfc5c060"
      }
    ],
    "chart_data":{
         "2022": [
                   {"label":"Jan", "value":500},
                   {"label":"Feb", "value":500},
                   {"label":"March", "value":500},  
                  {"label":"April", "value":500}
                 ],
         "2023": [
                   {"label":"Jan", "value":500},
                   {"label":"Feb", "value":500},
                   {"label":"March", "value":500},  
                  {"label":"April", "value":500}
                 ]
    },
    "createdAt": "2023-07-05T17:23:07.738Z",
    "updatedAt": "2023-07-08T16:05:31.249Z",
    "__v": 0
  }
]

请求载荷

{
  "userId": "123456789",
  "transactionId": "64a5bcbc4c28d90fdfc5c067",
  "label": "Jan",
  "year": "2022"
}

处理逻辑与实现(Node.js + Mongoose)

1. 定位文档并提取交易价格

先通过userId找到目标文档,筛选出待删除的交易记录以获取其价格:

const userDoc = await User.findOne({ userId: req.body.userId });
const targetTransaction = userDoc.transactions.find(t => t._id.toString() === req.body.transactionId);
if (!targetTransaction) {
  return res.status(404).json({ message: "交易记录不存在" });
}
const transactionPrice = targetTransaction.price;

2. 删除交易并截取数组

移除指定交易后,截取数组最后两个元素:

// 删除目标交易
userDoc.transactions = userDoc.transactions.filter(t => t._id.toString() !== req.body.transactionId);
// 保留最后两个元素
userDoc.transactions = userDoc.transactions.slice(-2);

3. 更新图表数据

找到指定年份和标签的图表项,减去交易价格:

const targetYearData = userDoc.chart_data[req.body.year];
if (targetYearData) {
  const targetMonth = targetYearData.find(item => item.label === req.body.label);
  if (targetMonth) {
    targetMonth.value -= transactionPrice;
  }
}

4. 保存并返回结果

保存更新后的文档,返回指定字段:

await userDoc.save();
res.json({
  transactions: userDoc.transactions,
  chart_data: userDoc.chart_data
});

最终返回结果

{
  "transactions": [
    {
      "title": "title_4",
      "price": 40,
      "_id": "64a5bcbc4c28d90fdfc5c061"
    },
    {
      "title": "title_5",
      "price": 40,
      "_id": "64a5bcbc4c28d90fdfc5c060"
    }
  ],
  "chart_data": {
    "2022": [
      {"label":"Jan", "value":460},
      {"label":"Feb", "value":500},
      {"label":"March", "value":500},
      {"label":"April", "value":500}
    ],
    "2023": [
      {"label":"Jan", "value":500},
      {"label":"Feb", "value":500},
      {"label":"March", "value":500},
      {"label":"April", "value":500}
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:15:01