如何在MongoDB嵌套文档中计算并存储商品totalPrice?
问题描述
我需要计算商品的totalPrice(数量×单价),并通过POST请求保存到MongoDB的Order嵌套文档中,但查询订单时totalPrice未被正确存储。期望每个商品的totalPrice能正确显示(比如数量3、单价123时显示369)。
相关代码
OrderSchema.js
const OrderSchema = new mongoose.Schema({ userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, products: [ { productId:{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, quantity: { type: Number, default: 1, }, sellerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, totalPrice: { type: Number, default: 0, } } ], }, {timestamps: true} ) export default mongoose.model('Order', OrderSchema)
前端提交代码(Order.js)
const handleSubmit = async (e) =>{ e.preventDefault() if(orderSummary?.location === ""){ toast.error("Please input location..") }else{ try { await userRequest.post(`/order`,{ userId: currentUser._id, products: cart.products.map((item) =>({ productId: item._id, quantity: item.quantity, sellerId: item.seller_id._id, totalPrice: Number(item.quantity * item._id.price) })), }) } catch (error) { toast.error("Please put a Location and Time!") } } }
当前返回数据
{ "_id": "63b1b4de5a95bd4df7f9443b", "userId": { "_id": "63b18af8363f51fa50801dd0", "studentId": "1234567892" }, "products": [ { "productId": { "_id": "63b16fc58fe585c7b81c748d", "title": "asd", "price": "123" }, "quantity": 3, "sellerId": { "_id": "63b160689f50f852e056afaf", "studentId": "1234567890" }, "_id": "63b1b4de5a95bd4df7f9443c" }, { "productId": { "_id": "63b16ff08fe585c7b81c7496", "title": "asd21", "price": "213" }, "quantity": 3, "sellerId": { "_id": "63b160689f50f852e056afaf", "studentId": "1234567890" }, "_id": "63b1b4de5a95bd4df7f9443d" } ], }
期望返回数据
{ "_id": "63b1b4de5a95bd4df7f9443b", "userId": { "_id": "63b18af8363f51fa50801dd0", "studentId": "1234567892" }, "products": [ { "productId": { "_id": "63b16fc58fe585c7b81c748d", "title": "asd", "price": "123" }, "quantity": 3, "sellerId": { "_id": "63b160689f50f852e056afaf", "studentId": "1234567890" }, "totalPrice": "369" }, { "productId": { "_id": "63b16ff08fe585c7b81c7496", "title": "asd21", "price": "213" }, "quantity": 3, "sellerId": { "_id": "63b160689f50f852e056afaf", "studentId": "1234567890" }, "totalPrice": "639" } ], }
修复方案
1. 修正前端计算逻辑
你在计算totalPrice时错误使用了item._id.price——item._id是商品的ObjectId,本身没有price属性,正确应该直接取购物车商品项自带的price字段。同时要注意price是字符串类型,需先转成数字再计算,避免字符串拼接错误。
修改前端map部分代码:
products: cart.products.map((item) =>({ productId: item._id, quantity: item.quantity, sellerId: item.seller_id._id, // 修复取值错误+类型转换 totalPrice: item.quantity * Number(item.price) })),
2. 统一数据类型(可选)
你的Schema中totalPrice定义为Number类型,但期望返回是字符串。如果要和期望结果一致,有两种选择:
- 前端计算后转成字符串:
totalPrice: String(item.quantity * Number(item.price)) - 修改Schema中
totalPrice的类型:totalPrice: { type: String, default: "0", }
3. 后端二次验证(可选)
为避免前端传入错误数据,建议在后端创建订单时重新计算totalPrice:
// 后端订单创建接口示例 router.post('/order', async (req, res) => { const { userId, products } = req.body; const processedProducts = products.map(prod => ({ ...prod, totalPrice: prod.quantity * Number(prod.price) })); const newOrder = new Order({ userId, products: processedProducts }); await newOrder.save(); res.status(201).json(newOrder); });
内容的提问来源于stack exchange,提问作者Zurcemozz
相关产品推荐
相关产品推荐

