如何使用nodejs express和mongoose将产品添加到购物车

时间:2019-12-04 11:16:26

标签: node.js express mongoose

我正在构建一个库存管理应用程序,并且我想创建一个类似于购物车/产品系统的功能。我处于将产品添加到购物车的阶段,似乎无法找出有效的代码。

const mongoose = require("mongoose");

const CartSchema = new mongoose.Schema(
  {
    active: Bolean,
    modifiedOn: Date,
    product: [
      {
        qunantity: String,
        name: String,
        price: number
      }
    ]
  },
  { timestamps: true }
);

module.exports = mongoose.model("Cart", CartSchema);

购物车控制器:

exports.postCart = asyncHandler(async (req, res, next) => {
  let cart = JSON.parse(req.body.cart);
  if (!cart) return res.json(products)
  for (var i = 0; i < products.length; i++) {
    id = products[i].id.toString();
    if (cart.hasOwnProperty(id)) {
      products[i].qty = cart[id]
      products.push(products[i]);
    }
  }
  return res.json(products);
})

正在尝试建立类似upsert的功能,以便为提供的userId创建文档,如果尚不存在。事实是我已经尝试过但无法解决,任何有想法的人都会感激

2 个答案:

答案 0 :(得分:1)

我认为购物车中的userId字段在购物车系统中是必须的。

所以我会这样设计我的模式:

const mongoose = require("mongoose");

const CartSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    },
    products: [
      {
        productId: Number,
        quantity: Number,
        name: String,
        price: Number
      }
    ],
    active: {
      type: Boolean,
      default: true
    },
    modifiedOn: {
      type: Date,
      default: Date.now()
    }
  },
  { timestamps: true }
);

module.exports = mongoose.model("Cart", CartSchema);

请注意:

  1. 我假设您有一个User模型,如果您的用户使用其他模型,则可以更新userId字段中的参考。
  2. 我将数量字段的类型更改为Number
  3. 我将product字段重命名为products,因为它是一个数组。

使用此架构,我将创建一条类似这样的路线以将商品添加到购物车:

router.post("/cart", async (req, res) => {
  const { productId, quantity, name, price } = req.body;

  const userId = "5de7ffa74fff640a0491bc4f"; //TODO: the logged in user id

  try {
    let cart = await Cart.findOne({ userId });

    if (cart) {
      //cart exists for user
      let itemIndex = cart.products.findIndex(p => p.productId == productId);

      if (itemIndex > -1) {
        //product exists in the cart, update the quantity
        let productItem = cart.products[itemIndex];
        productItem.quantity = quantity;
        cart.products[itemIndex] = productItem;
      } else {
        //product does not exists in cart, add new item
        cart.products.push({ productId, quantity, name, price });
      }
      cart = await cart.save();
      return res.status(201).send(cart);
    } else {
      //no cart for user, create new cart
      const newCart = await Cart.create({
        userId,
        products: [{ productId, quantity, name, price }]
      });

      return res.status(201).send(newCart);
    }
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

我假设您已经具有登录用户的ID,我设置了一个硬编码的userId。

一些测试:

我们第一次为用户添加产品到购物车

{
    "productId": 1,
    "quantity": 1,
    "name": "product 1",
    "price": 11
}

响应如下:

{
    "active": true,
    "modifiedOn": "2019-12-04T19:02:12.673Z",
    "_id": "5de802bbc68b882d4803473f",
    "userId": "5de7ffa74fff640a0491bc4f",
    "products": [
        {
            "_id": "5de802bbc68b882d48034740",
            "productId": 1,
            "quantity": 1,
            "name": "product 1",
            "price": 11
        }
    ],
    "createdAt": "2019-12-04T19:02:19.567Z",
    "updatedAt": "2019-12-04T19:02:19.567Z",
    "__v": 0
}

然后我们添加另一种产品:

{
    "productId": 2,
    "quantity": 2,
    "name": "product 2",
    "price": 22
}

响应如下:

{
    "active": true,
    "modifiedOn": "2019-12-04T19:02:12.673Z",
    "_id": "5de802bbc68b882d4803473f",
    "userId": "5de7ffa74fff640a0491bc4f",
    "products": [
        {
            "_id": "5de802bbc68b882d48034740",
            "productId": 1,
            "quantity": 1,
            "name": "product 1",
            "price": 11
        },
        {
            "_id": "5de802e3c68b882d48034741",
            "productId": 2,
            "quantity": 2,
            "name": "product 2",
            "price": 22
        }
    ],
    "createdAt": "2019-12-04T19:02:19.567Z",
    "updatedAt": "2019-12-04T19:02:59.703Z",
    "__v": 1
}

现在让我们尝试将productId = 2的数量更改为1。

{
    "productId": 2,
    "quantity": 1,
    "name": "product 2",
    "price": 22
}

响应如下:

{
    "active": true,
    "modifiedOn": "2019-12-04T19:02:12.673Z",
    "_id": "5de802bbc68b882d4803473f",
    "userId": "5de7ffa74fff640a0491bc4f",
    "products": [
        {
            "_id": "5de802bbc68b882d48034740",
            "productId": 1,
            "quantity": 1,
            "name": "product 1",
            "price": 11
        },
        {
            "_id": "5de802e3c68b882d48034741",
            "productId": 2,
            "quantity": 1,
            "name": "product 2",
            "price": 22
        }
    ],
    "createdAt": "2019-12-04T19:02:19.567Z",
    "updatedAt": "2019-12-04T19:03:42.506Z",
    "__v": 1
}

如您在响应中看到的,productId = 2的数量更改为1。

答案 1 :(得分:1)

您的购物车模型应如下所示:


    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;

    let ItemSchema = new Schema({
        productId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Product",
        },
        quantity: {
            type: Number,
            required: true,
            min: [1, 'Quantity can not be less then 1.']
        },
        price: {
            type: Number,
            required: true
        },
        total: {
            type: Number,
            required: true,
        }
    }, {
        timestamps: true
    })
    module.exports = mongoose.model('item', ItemSchema);

    const CartSchema = new Schema({
        userId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },

        items: [ItemSchema],

        subTotal: {
            default: 0,
            type: Number
        }
    }, {
        timestamps: true
    })
    module.exports = mongoose.model('cart', CartSchema);

之后,您可以定义添加方法:


    exports.addItemToCart = async (req, res) => {
        const {
            userId,
            productId
        } = req.body;
        const quantity = Number.parseInt(req.body.quantity);

        try {
            // -------Get users Cart ------
            let cart = await Cart.findOne({
                userId: userId
            })

            //-----Get Selected Product Details ----
            const productDetails = await Product.findById(productId);

            //-- Check if cart Exists and Check the quantity if items -------
            if (!cart && quantity  item.productId == productId);

                //------this removes an item from the the cart if the quantity is set to zero,We can use this method to remove an item from the list  --------
                if (indexFound !== -1 && quantity  item.total).reduce((acc, next) => acc + next);
                }

                //----------check if product exist,just add the previous quantity with the new quantity and update the total price-------
                else if (indexFound !== -1) {
                    cart.items[indexFound].quantity = cart.items[indexFound].quantity + quantity;
                    cart.items[indexFound].total = cart.items[indexFound].quantity * productDetails.price;
                    cart.items[indexFound].price = productDetails.price
                    cart.subTotal = cart.items.map(item => item.total).reduce((acc, next) => acc + next);
                }

                //----Check if Quantity is Greater than 0 then add item to items Array ----
                else if (quantity > 0) {
                    cart.items.push({
                        productId: productId,
                        quantity: quantity,
                        price: productDetails.price,
                        total: parseInt(productDetails.price * quantity)
                    })
                    cart.subTotal = cart.items.map(item => item.total).reduce((acc, next) => acc + next);
                }
                //----if quantity of price is 0 throw the error -------
                else {
                    return res.status(400).json({
                        type: "Invalid",
                        msg: "Invalid request"
                    })
                }
                let data = await cart.save();
                res.status(200).json({
                    type: "success",
                    mgs: "Process Successful",
                    data: data
                })
            }
            //------------ if there is no user with a cart...it creates a new cart and then adds the item to the cart that has been created------------
            else {
                const cartData = {
                    userId: userId,
                    items: [{
                        productId: productId,
                        quantity: quantity,
                        total: parseInt(productDetails.price * quantity),
                        price: productDetails.price
                    }],
                    subTotal: parseInt(productDetails.price * quantity)
                }
                cart = new Cart(cartData);
                let data = await cart.save();
                res.json(data);
            }
        } catch (err) {
            console.log(err)
            res.status(400).json({
                type: "Invalid",
                msg: "Something Went Wrong",
                err: err
            })
        }
    }