Angular+MongoDB:创建用户购物车时无法添加商品详情的问题排查
电商购物车添加商品问题排查
问题描述
我开发的电商网站,前端使用Angular,后端基于MongoDB、Node.js和Express实现。用户点击添加商品到购物车时,虽然能成功创建购物车,但无法正确添加商品详情。以下是相关代码与数据,请求帮忙排查问题。
Schema代码
const mongoose = require("mongoose"); const User = require('../../app/backend/users/user.model') const Schema = mongoose.Schema; const CartSchema = new mongoose.Schema ({ userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, products: [ { name:{ type: String, }, size:{ type:String, }, imageUrl:{ type: String, }, price:{ type: Number, } } ], active: { type: Boolean, default: true }, modifiedOn: { type: Date, default: Date.now } }, { timestamps: true } ); module.exports = mongoose.model('cartItem', CartSchema, "cartitems");
路由代码
router.post('/getProducts/addtocart:id', async(req, res)=> { var _id = req.params.id; //test this const name = req.body.name; const size = req.body.size; const imageUrl = req.body.imageUrl; const price = req.body.price; const description = req.body.description; userId =({"_id" : ObjectId("65868ffd5a346036b447937a")}); try{ // -------Get users Cart ------ let cart = await cartItem.findOne({userId:userId}); if(cart) { //means cart is not null // cart exist for user let itemIndex = cart.products.findIndex(p => p.name == name); //----------check if product exist if (itemIndex > -1) { //product exists in the cart, update the quantity *** have to add this*** // cart.product[itemIndex].price = productDetails.price add ths later let productItem = cart.products[itemIndex]; cart.products[itemIndex] = productItem; } else{ //product does not exist cart.products.push({ name, size, imageUrl, price}); } cart = await cart.save(); console.log("What is cart" + "" + "" + cart ); return res.status(201).send(cart); } else { //no cart for user create new cart const newCart = await cartItem.create({ userId, _id, products: [ { name, size, imageUrl, price } ] }); cart.products.push({ name, size, imageUrl, price}); /*mongoose.connect(mongoURI, function(err, db){ assert.ok("1" == 1 ); db.collection('cartitems').updateOne({_id:_id}, {$set: {name:name, size:size, imageUrl:imageUrl, price:price}}), //{ $push:({name:name, size:size, imageUrl:imageUrl, price:price})} newCart.products.push({productId, name, size, imageUrl, price}); //db.close(); });*/ /* I get the req.body for _id console.log('Request body output ' + JSON.stringify(req.body)); console.log("Whats in newCart", newCart);*/ return res.status(201).send(newCart) } } catch (err) { console.log(err); res.status(500).send("Something went wrong"); } });
商品数据
{ _id: ObjectId("65f991e01f28a7f454777cd8"), name: 'Grey Jumper', size: '', description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,when an unknown printer took a galley of type and scrambled it to make a type specimen book.", imageUrl: 'http://localhost:4200/assets/greyofftheshoulder.png', price: 99 }
请求Payload
{ "_id": "65f991e01f28a7f454777cd8", "name": "Grey Jumper", "size": "M", "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", "imageUrl": "http://localhost:4200/assets/greyofftheshoulder.png", "price": 99 }
问题排查关键点
userId查询条件错误:
代码中userId =({"_id" : ObjectId("65868ffd5a346036b447937a")});将userId定义为包含_id的对象,但Schema里userId字段类型是ObjectId,正确写法应为userId = ObjectId("65868ffd5a346036b447937a");。原写法会导致findOne({userId:userId})无法匹配到正确的用户购物车,每次都会创建新购物车。创建新购物车后存在无效代码:
在else块创建完newCart后,执行了cart.products.push(...),但此时cart变量未定义,会抛出错误导致逻辑中断,影响商品添加结果。需删除这行无效代码。路由路径参数格式错误:
路由路径'/getProducts/addtocart:id'缺少斜杠,正确格式应为'/getProducts/addtocart/:id',否则req.params.id可能无法正确获取参数值。已有购物车时的无效更新逻辑:
当商品已存在于购物车时,代码仅将原商品对象重新赋值,未做任何实际更新(如尺寸、数量)。建议改用商品ID作为判断依据,同时补充属性或数量的更新逻辑。
内容的提问来源于stack exchange,提问作者user2280852
相关产品推荐
相关产品推荐

