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

8SI*_*INS 1 mongoose node.js express

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

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);
Run Code Online (Sandbox Code Playgroud)

推车控制器:

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);
})
Run Code Online (Sandbox Code Playgroud)

我正在尝试设置一个类似 upsert 的函数,以便为提供的 userId 创建文档,如果一个尚不存在。事实是,我已经尝试过但无法弄清楚,任何有想法的人都会受到赞赏

Sul*_*Sah 10

我认为购物车中的 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);
Run Code Online (Sandbox Code Playgroud)

注意:

  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");
  }
});
Run Code Online (Sandbox Code Playgroud)

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

一些测试:

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

{
    "productId": 1,
    "quantity": 1,
    "name": "product 1",
    "price": 11
}
Run Code Online (Sandbox Code Playgroud)

响应将是这样的:

{
    "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
}
Run Code Online (Sandbox Code Playgroud)

然后让我们添加另一个不同的产品:

{
    "productId": 2,
    "quantity": 2,
    "name": "product 2",
    "price": 22
}
Run Code Online (Sandbox Code Playgroud)

响应将是这样的:

{
    "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
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "productId": 2,
    "quantity": 1,
    "name": "product 2",
    "price": 22
}
Run Code Online (Sandbox Code Playgroud)

响应将是这样的:

{
    "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
}
Run Code Online (Sandbox Code Playgroud)

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