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

Mongoose实现购物车匹配item_id更新数量否则新增对象的方案

Mongoose购物车增量更新实现方案

前置优化建议

你当前定义的cartSchema中qty字段为String类型,无法直接执行加法运算,会出现字符串拼接的异常问题,建议先将qty调整为Number类型:

// 修改后的cartSchema
import mongoose from "mongoose";
const { Schema } = mongoose;

export const cartSchema = new Schema({
  item_id: {
    type: String,
  },
  qty: {
    type: Number,
    default: 1
  },
});

实现方式1:分步骤原子操作(兼容性好,易理解)

先尝试更新已存在的商品条目,若没有匹配到条目再执行新增操作,全程原子操作避免并发数据异常:

// 假设你已通过mongoose.model导出User模型,入参为用户id和要添加的商品item_id
async function updateUserCart(userId, targetItemId) {
  // 第一步:尝试更新已存在的商品数量
  const updateRes = await User.updateOne(
    { _id: userId, "cart.item_id": targetItemId },
    { $inc: { "cart.$.qty": 1 } }
  );
  // 第二步:没有匹配到已存在条目则新增
  if (updateRes.modifiedCount === 0) {
    await User.updateOne(
      { _id: userId },
      { $push: { cart: { item_id: targetItemId, qty: 1 } } }
    );
  }
}

实现方式2:单请求聚合管道更新(MongoDB 4.2+支持)

只需一次数据库请求即可完成全部逻辑,性能更好:

async function updateUserCart(userId, targetItemId) {
  await User.updateOne(
    { _id: userId },
    [
      {
        $set: {
          cart: {
            $cond: {
              // 判断购物车是否已存在该商品
              if: { $in: [targetItemId, "$cart.item_id"] },
              // 存在则遍历更新对应条目的数量
              then: {
                $map: {
                  input: "$cart",
                  in: {
                    $cond: [
                      { $eq: ["$$this.item_id", targetItemId] },
                      { $mergeObjects: ["$$this", { qty: { $add: ["$$this.qty", 1] } }] },
                      "$$this"
                    ]
                  }
                }
              },
              // 不存在则追加新条目
              else: { $concatArrays: ["$cart", [{ item_id: targetItemId, qty: 1 }]] }
            }
          }
        }
      }
    ]
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:18:03