我正在嘗試將產品添加到 mongodb 的購物車中,但我撰寫的代碼不起作用。它以前可以作業,但是當我從本地 mongodb 切換到 mongodb atlas cloud 然后回到本地 mongodb 時,它開始出現問題,因為它不會使用重定向到“/”根目錄時創建的購物車,而是繼續創建一個新的購物車每次將產品添加到購物車時,都會有一個新的 req.session.cartId 屬于它。我在這一部分遇到了很多問題,這是我專案的最后一部分,在實時托管之前開始作業。任何幫助表示贊賞。謝謝你。
const express = require('express');
const Carts = require('../repo/carts');
const Product = require('../repo/products');
const cartShowTemplate = require('../views/carts/show');
const router = express.Router();
let cart;
router.post('/cart/products', async (req, res) => {
try {
cart = await Carts.findById(req.session.cartId);
// Check if cart exists
if (!cart) {
// Create new cart
cart = await Carts.create({
_id: req.session.cartId,
items: [],
});
}
// Check if product is present
const productIndex = cart.items.findIndex(
(item) => item._id === req.body.productId
);
if (productIndex === -1) {
// Create new product
cart.items.push({
_id: req.body.productId,
quantity: 1,
});
} else {
// Update existing product
cart.items[productIndex].quantity = 1;
}
// Save updated cart
await cart.save();
console.log(cart);
res.status(200).send('product added to cart!!');
} catch (err) {
res.status(500).send('there was an error');
}
});
module.exports = router;
陣列的示例
添加了正確的產品,但每次都會創建一個具有新 ID 的新購物車,而不是使用同一個購物車。我不確定這是否有幫助,但是當我使用 console.log(req.sessionID) 時,我注意到它每次 console.logged 時都會顯示相同的 ID,但是當 console.logging (req.session.cartId) 顯示為未定義時在它顯示ID之前。

購物車模式
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
_id: String,
items: [
{ quantity: Number, _id: String }
]
});
const Carts = new mongoose.model('Carts', cartSchema);
module.exports = Carts;
uj5u.com熱心網友回復:
試試這個邏輯:
router.post('/cart/products', async (req, res) => {
try {
let cart = await Carts.findById(req.session.cartId);
// Check if cart exists
if (!cart) {
// Create new cart
cart = await Carts.create({
_id: req.session.cartId,
items: [],
});
}
// Check if product is present
const productIndex = cart.items.findIndex(
(item) => item._id === req.body.productId
);
if (productIndex === -1) {
// Create new product
cart.items.push({
_id: req.body.productId,
quantity: 1,
});
} else {
// Update existing product
cart.items[productIndex].quantity = 1;
}
// Save updated cart
await cart.save();
res.status(200).send('product added to cart!!');
} catch (err) {
res.status(500).send('there was an error');
}
});
uj5u.com熱心網友回復:
我不太確定這一點,但看起來您可能對異步方法有疑問。
此方法既沒有等待也沒有回呼函式,因此行程將繼續(并且可能完成)而不等待它完成。
Carts.updateOne(
{_id: req.body.productId },
{ $inc: { quantity: 1 } }
);
https://mongoosejs.com/docs/api.html#query_Query-updateOne(如果你看那里的例子,它正在等待中)
另一方面,你應該得到這個塊:
Carts.updateOne(
{ _id: foundCart._id },
{
$push: {
items: {
_id: req.body.productId,
quantity: 1,
},
},
},
(err, updatedCart) => {
if (err) {
console.log(err);
}
}
);
在else塊內。因此,如果您找到帶有 id 的現有商品,您會嘗試更新它,但只有當您沒有找到它時,您才會將新商品推送到購物車中。
它應該看起來像這樣:
if (check.includes(req.body.productId)) {
console.log('MATCH FOUND');
Carts.updateOne(
{_id: req.body.productId },
{ $inc: { quantity: 1 } }
);
} else {
Carts.updateOne(
{ _id: foundCart._id },
{
$push: {
items: {
_id: req.body.productId,
quantity: 1,
},
},
},
(err, updatedCart) => {
if (err) {
console.log(err);
}
}
);
}
我希望這能解決問題!:D
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/528765.html
