我试图在mongodb中将产品添加到购物车,但将获得无法读取的属性,find is undefined

yvgpqqbh  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(165)

我尝试将产品添加到存储在mongodb中的购物车,但出现“TypeError:无法读取未定义的属性(阅读“查找”)”将发生,导致它不添加任何产品到购物车。我已经花了一整天试图让这个工作没有运气,任何帮助将不胜感激。

  1. const express = require('express');
  2. const Carts = require('../repo/carts');
  3. // const cartShowTemplate = require('../views/carts/show');
  4. const router = express.Router();
  5. let cart;
  6. router.post('/cart/products', async (req, res) => {
  7. if (!req.session.cartId) {
  8. cart = await Carts.create({ items: [] });
  9. req.session.cartId = cart._id;
  10. } else {
  11. cart = await Carts.find(req.session.cartId);
  12. }
  13. console.log(cart);
  14. // look thru cart and find item with id property equal to req.body.productId
  15. property
  16. //if item exists increment by 1 and save cart
  17. //add new product to items array
  18. const existingItem = cart.items.find(item => item._id === req.body.productId)
  19. if (existingItem) {
  20. existingItem++;
  21. } else {
  22. cart.items.push({ id: req.body.productId, quantity: 1 });
  23. }
  24. await Carts.updateOne(cart._id, {
  25. items: cart.items
  26. });
  27. res.send('product added to cart!!');
  28. });
  29. module.exports = router;

carts mongodb模式

  1. const mongoose = require('mongoose');
  2. const cartSchema = new mongoose.Schema({
  3. _id: String,
  4. items: [
  5. { quantity: Number, _id: String },
  6. ]
  7. });
  8. const Carts = new mongoose.model('Carts', cartSchema);
  9. module.exports = Carts;
vlf7wbxs

vlf7wbxs1#

此行可能存在问题:findById
如果按id查找,则应使用findById,而不是findfindById.find({_id: req.session.cartId})的快捷方式,使用find时,它将需要一个查询对象。

相关问题