【问题标题】:Express/Mongo - Updating cartItems quantityExpress/Mongo - 更新 cartItems 数量
【发布时间】:2021-05-27 12:16:16
【问题描述】:

我是使用 express 和 mongoose 的初学者。截至目前,我正在创建一个 3 天前开始的电子商务项目。我在向后端 REST API 添加数量时遇到问题,对代码进行故障排除。 你能帮我弄清楚这件事吗?提前谢谢你

购物车型号:

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
    cartItems: [
        {
            product_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true}, // This foreign key to product _id
            quantity: {type: Number, default: 1, required: true},
            price: {type: Number, required: true}
        }
    ]
}, {timestamps: true});

module.exports = mongoose.model('Cart', cartSchema);

我的路由器:

const express = require('express');
const { addItemToCart } = require('../controller/controller_cart.js');
const router = express.Router();

router.post('/user/cart/addtocart', addItemToCart );

module.exports = router;

我的控制器:

const Cart = require("../models/model_cart.js");

exports.addItemToCart = (req, res) => {
  Cart.findOne({ user: req.user._id }).exec((error, cart) => {
    if (error) return res.status(400).json({ error });
    if (cart) {
      const product_id = req.body.cartItems.product_id;
      const item = cart.cartItems.find((c) => c.product_id == product_id);
      if (item) {
        Cart.findOneAndUpdate(
          { user: req.user._id, "cartItems.product_id": product_id },
          {
            $cartItems: {
                  ...req.body.cartItems,
                  quantity: item.quantity + req.body.cartItems.quantity
            },
          }
        ).exec((error, _cart) => {
          if (error) return res.status(400).json({ error });
          if (_cart) {
            return res.status(201).json({ cart: _cart });
          }
        });
        // if user cart does't exist create a list of cart for the user
      } else {
        Cart.findOneAndUpdate(
          { user: req.user._id },
          {
            $push: {
              cartItems: req.body.cartItems,
            },
          }
        ).exec((error, _cart) => {
          if (error) return res.status(400).json({ error });
          if (_cart) {
            return res.status(201).json({ cart: _cart });
          }
        });
      }
    } else {
      // if cart not exist create a new cart
      const cart = new Cart({
        user: req.user._id,
        cartItems: req.body.cartItems,
      });
      cart.save((error, cart) => {
        if (error) return res.status(400).json({ error });
        if (cart) {
          return res.status(200).json({ cart });
        }
      });
    }
  });
};

回应:

{
    "cart": {
        "_id": "606d5eb292811a0a849a1df8",
        "user": "606ad588d3ab5819b8e33a00",
        "cartItems": [
            {
                "quantity": 1,
                "_id": "606d5eb292811a0a849a1df9",
                "product_id": "606c3c7e5c932b33d49b2d05",
                "price": 4142
            },
            {
                "quantity": 1,
                "_id": "606d5eb492811a0a849a1dfa",
                "product_id": "606c3c7e5c932b33d49b2d05",
                "price": 4142
            }
        ],
        "createdAt": "2021-04-07T07:26:42.867Z",
        "updatedAt": "2021-04-07T07:26:44.362Z",
        "__v": 0
    }
}

响应应该添加数量而不是创建另一个数组。

【问题讨论】:

    标签: express mongoose mongoose-schema


    【解决方案1】:

    试试cartItems.$ 代替 $cartItems:

    在你的控制器中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2017-01-14
      相关资源
      最近更新 更多