【发布时间】:2021-01-27 16:46:37
【问题描述】:
我尝试了很多东西,但无法为“添加到购物车”功能编写代码。你能帮我做这件事吗?
这是购物车模型:
var cartSchema = new mongoose.Schema({
owner: {type: mongoose.Schema.Types.ObjectID, ref: 'User'},
totalPrice: {type: Number, default: 0},
items: [{
item: {type: mongoose.Schema.Types.ObjectID, ref: 'Product'},
qty: {type: Number, default: 1},
price: {type: Number, default: 0}
}]})
这是产品型号:
var productSchema = new mongoose.Schema({
category: String,
name: String,
price: Number,
image: String,
description: String,
stock: Number,
reviews: [
{
type: mongoose.Schema.Types.ObjectID, ref: 'Review'
}
]
})
编辑(详细解释):
第 1 步:当我单击添加到购物车按钮时,它应该发出“获取”请求,并且应该发生以下事情:
- 获取登录用户的id,即req.user._id
- 将点击的产品存储在购物车模型中的 items 数组中
- 它应该根据所需的产品数量计算价格,即 qty*price 并将其存储在购物车模型中 items 数组的“价格”中
step2:当另一个产品被添加到购物车时,它应该遵循 step1 中提到的所有步骤,除此之外它还应该计算购物车的总价格,即 totalPrice = qty1xproduct1_price + qty2xproduct2_price + 。 ... 并将其存储在购物车模型的“totalPrice”中。
第三步:当我点击查看购物车时,即 router.get("/cart"),这应该把我带到购物车,它应该检查登录用户并显示属于该用户的购物车,即它应该检查 Cart.owner 并向我显示购物车的所有详细信息。例如:(
-
简述产品详情
-
数量
-
价格 = 数量 x 价格_每件产品
-
所有这些产品的最终总价
)
编辑 3:
这是添加到购物车的按钮:
<form action="/product/<%= product._id %>/addCart" method="POST">
<select name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button>Add to cart</button>
</form>
这是购物车路线:
router.post("/product/:id/addCart", async (req, res) => {
const quantity = req.body;
Product.findById(req.params.id, function(err, foundProduct){
if(err){
console.log(err);
}
const product = {
item: foundProduct._id,
qty: quantity,
price: foundProduct.price * quantity
}
Cart.owner = req.user._id;
Cart.itmes.push(product);
Cart.save();
res.redirect("/cart");
})
})
router.get("/cart", function(req, res){
Cart.find({owner: req.user._id}, function(err, userCart){
if(err){
console.log(err);
}
const pPrice = userCart.items.map(p => p.price);
const totalPrice = pPrice.reduce((a, b) => a + b, 0);
userCart.totalPrice = totalPrice;
userCart.save()
res.render("cart", {cart: userCart});
})
})
显示Cannot POST /product/5f80569156202d0a624d35af/addCart
【问题讨论】:
-
res.redirect("/cart")? -
是 Res.redirect("/cart")
-
问题解决了 :)
-
你能解释一下吗?!
-
好吧,你问
It would redirect to "/cart" after adding the product,给你。res.redirect("/cart"),这就是答案