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

使用Mongoose关联Menu与Cart集合并更新菜品数量

餐厅购物车菜单数量匹配实现方案

需求概述

将Menu集合中每个菜品的Quantity字段更新为:若该菜品存在于Cart集合中,则对应Cart条目的menuQuantity值;若不存在,则保持0。


方案一:前端JavaScript处理

先将Cart数据转换成以menuId为键的映射表,再遍历Menu列表更新Quantity,逻辑简单高效:

// 先将cart转换为menuId -> menuQuantity的映射
const cartMap = new Map(cart.map(item => [item.menuId, item.menuQuantity]));

// 遍历menus更新Quantity字段
const result = menus.map(menu => ({
  ...menu,
  Quantity: cartMap.get(menu._id) || 0
}));

console.log(result);

这段代码会直接输出预期结果,适合前端渲染前的数据预处理。


方案二:MongoDB聚合查询(数据库层面处理)

如果需要直接从数据库获取处理后的结果,可以用MongoDB聚合管道,通过关联查询后处理字段:

db.menus.aggregate([
  {
    $lookup: {
      from: "cart",
      localField: "_id",
      foreignField: "menuId",
      as: "cartItem"
    }
  },
  {
    $addFields: {
      Quantity: {
        $cond: {
          if: { $gt: [{ $size: "$cartItem" }, 0] },
          then: { $arrayElemAt: ["$cartItem.menuQuantity", 0] },
          else: 0
        }
      }
    }
  },
  {
    $project: {
      cartItem: 0 // 移除临时关联的cartItem字段
    }
  }
]).toArray();

该方案适合后端直接查询出处理好的数据返回,无需额外内存处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:50:30