首页 > 解决方案 > 用于购物车的 Nodejs MongoDB 模式、路由和控制器

问题描述

我有一个工作车模式,如下所示:

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

const ItemSchema = new mongoose.Schema({

  
    gameId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Game"
    },
    quantity: 
      {
        type: Number,
        required: true,
        min: [1, 'Quantity can not be lesser than one'],
      },
    price: {
      type: Number,
      required: true
    },
    total: {
      type: Number,
      required: true
    }
  },
  { 
    timestamps: true 
  });

  const CartSchema = new Schema({

    items: [ItemSchema],
    subTotal: {
      default: 0,
      type: Number
    }
  },
  { 
    timestamps: true 
  });




const Cart = mongoose.model('cart', CartSchema);
module.exports = Cart;

我知道我缺少“用户”对象,如下所示:

user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },

我在网上关注的文章中犯了这个错误,现在我对如何处理我的控制器文件感到困惑,如下所示:

PS:任何你看到游戏的地方都是产品

const cartRepository = require("../routes/cartRepository")

const gameRepository = require("../routes/repository")

exports.addItemToCart = async (req, res) => {
    const {
        gameId
    } = req.body;

   const quantity = Number.parseInt(req.body.quantity);

   try {
       let cart = await cartRepository.cart();

       let gameDetails = await gameRepository.gameById(gameId);

       if (!gameDetails) {
        
        return res.status(500).json({
            type: "Not Found",
            msg: "Invalid request"
        })
       }
       // if cart exists

       else if (cart) {

      // check if index exists
      const indexFound = cart.items.findIndex(item => {

        item.gameId === gameId
      });
        

      // This removes an item from 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 <= 0) {
          cart.items.splice(indexFound, 1);
          if (cart.items.length == 0) {
              cart.subTotal = 0;
          } else {
              cart.subTotal = cart.items.map(item => item.subTotal).reduce((acc, next) => acc + next)
          }
      }

        //  Check if product exist,
        // 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 * gameDetails.price;

            cart.items[indexFound].price = gameDetails.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({
                gameId: gameId,
                quantity: quantity,
                price: gameDetails.price,
                total: parseInt(gameDetails.price * quantity)
            })
            cart.subTotal = cart.items.map(item => item.total).reduce((acc, next) => acc + next);
        }

        // if quantity of price is 0 throw error

        else {
            return res.status(400).json({
                type: "Invalid",
                msg: "Invalid request"
            })
        }
        let data = await cart.save();
        res.status(200).json({
            type: "success",
            msg: "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 = {
               items: [{
                   gameId: gameId,
                   quantity: quantity,
                   total: parseInt(gameDetails.price * quantity),
                   price: gameDetails.price
               }],
               subTotal: parseInt(gameDetails.price * quantity)
           }
           cart = await cartRepository.addItem(cartData)

           // let data = await cart.save();
           res.json(cart);
       }
   } catch (err) {
       console.log(err)
       res.status(400).json({
           type: "Invalid",
           msg: "Something went wrong",
           err: err
       })
   }

}

exports.getCart = async (req, res) => {
    try {
        let cart = await cartRepository.cart()
        if (!cart) {
            return res.status(400).json({
                type: "invalid",
                msg: "Cart not found",
            })
        }
        res.status(200).json({
            status: true,
            data: cart
        })
    } catch (err) {
     console.log(err)

     res.status(400).json({
         type: "Invalid",
         msg: "Something went wrong",
         err: err
     })
    }
}


exports.emptyCart = async (req, res) => {
    try {
        let cart = await cartRepository.cart();
        cart.items = [];
        cart.subTotal = 0;

        let data = await cart.save();
        res.status(200).json({
            type: "Success",
            msg: "Cart has been emptied",
            data: data
        })
    } catch (err) {
        console.log(err)

        res.status(400).json({
            type: "Invalid",
            msg: "Something went wrong",
            err: err
        })
    }
}

当我测试它时它可以工作,但有很多缺失,因为它不针对任何用户

PS:我已经准备好我的用户认证 API。

如果可以提供更多信息,我还有我的 cartRoute 和存储库文件

存储库.js

const Cart = require('../models/cartModel')

exports.cart = async () => {
    const carts = await Cart.find().populate({
        path: "items.gameId",
        select: "name price total"
    });
    return carts[0];
}

exports.addItem = async payload => {
    const newItem = await Cart.create(payload);
    return newItem
}

购物车路由.js

const express = require('express');
const router =  express.Router();
const cartController = require("../controller/cartController")

router.post("/cart", cartController.addItemToCart)
router.get("/cart", cartController.getCart);
router.delete("/empty-cart", cartController.emptyCart)
  module.exports = router;
  

我提前感谢您的所有帮助。

如果需要更多信息才能使其有意义,请随时与我们联系。谢谢

标签: javascriptnode.jsmongodbcartmongoose-schema

解决方案


推荐阅读