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

MongoDB+Angular:如何生成新Object ID插入重复商品至购物车

解决方案:同商品不同尺寸独立加入购物车

你的思路完全可行——同一商品的不同尺寸属于独立的购物车条目,生成新ObjectID来区分这些条目是正确的做法。下面是修正后的代码和关键说明:

核心问题修正

  1. 移除重复的Mongoose连接:项目启动时已经完成数据库连接,无需在每个请求中重复调用mongoose.connect
  2. 获取客户端传来的尺寸参数:从请求体req.body中读取前端提交的尺寸信息
  3. 完整插入购物车条目:不能只插入新ID,需要把商品信息、尺寸、数量等完整数据存入购物车

修改后的代码

router.post('/getProducts/addtocart/:_id', async(req, res) => {
  try {
    const productId = req.params._id;
    // 从请求体获取前端传来的尺寸参数
    const { size } = req.body;
    // 查询商品信息
    const product = await Products.findById(productId);

    if (!product) {
      return res.status(404).json({ message: '商品不存在' });
    }

    // 创建新的购物车条目,生成唯一ObjectID
    const newCartItem = new Cart({
      _id: new mongoose.Types.ObjectId(), // 生成新ID
      productId: product._id,
      size: size,
      quantity: 1, // 默认数量1
      // 按需复制商品的其他信息,比如名称、价格
      name: product.name,
      price: product.price,
      image: product.image
    });

    // 保存到购物车
    await newCartItem.save();
    res.status(200).json({ message: '商品已添加到购物车', item: newCartItem });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: '添加购物车失败' });
  }
});

关键说明

  • Cart模型定义参考:确保你的Cart Schema包含对应字段
    const cartSchema = new mongoose.Schema({
      productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Products', required: true },
      size: { type: String, required: true }, // 尺寸字段,必填
      quantity: { type: Number, default: 1 },
      name: String,
      price: Number,
      image: String
    });
    
    const Cart = mongoose.model('Cart', cartSchema);
    
  • 前端请求要求:前端发送POST请求时,需要在请求体中包含size参数(比如{ size: 'M' })
  • 可选优化:同尺寸商品数量累加:如果需要判断「同一商品同一尺寸」是否已存在,可以在保存前先查询:
    const existingItem = await Cart.findOne({ productId, size });
    if (existingItem) {
      // 如果同尺寸已存在,直接增加数量
      existingItem.quantity += 1;
      await existingItem.save();
      return res.status(200).json({ message: '商品数量已增加', item: existingItem });
    }
    // 不存在则创建新条目
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:25:17