In my current task, I need to:
- Generate an order based on the items in my shopping cart
- Include the relevant object attributes in the order response based on the selection in the "select" option
- Ultimately, I aim to clear or delete the cart once the order is created
Although I have attempted the following steps, I have encountered several issues:
- The response returned is not populated even though the
prevProductsQuantity
constant contains data - Despite creating the function cartClear to delete the cart document based on its ID, the function is not functioning as expected
- I seem to be able to create duplicate orders, suggesting a need for conditional handling, but I am unsure where to implement it
Desired response structure:
{
"success": true,
"data": {
"_id": "607ed5c425ae063f7469a807",
"userId": "6071aed0ed7ec9344cf9616c",
"productsQuantity": [
{
"_id": "607f2507994d5e4bf4d91879",
"productId": {
"productRef": "463b8bb7-6cf6-4a97-a665-ab5730b69ba2",
"productName": "table",
"brand": "boehm llc",
"price": 713,
"__v": 0,
"createdAt": "2021-04-09T18:31:43.430Z",
"updatedAt": "2021-04-09T18:31:43.430Z"
},
"quantity": 2,
"updatedAt": "2021-04-21T15:12:51.894Z",
"createdAt": "2021-04-21T15:12:51.894Z"
}
],
"__v": 0
}
++ Clearing the Cart ++
Current response received:
{
"success": true,
"data": {
"state": "pending-payment",
"_id": "6080507a0c758608d0dc585c",
"userId": "6071aed0ed7ec9344cf9616c",
"totalPrice": 1426,
"productsQuantity": [
{
"_id": "607f2507994d5e4bf4d91879",
"productId": "60709d8f24a9615d9cff2b69",
"quantity": 2,
"updatedAt": "2021-04-21T15:12:51.894Z",
"createdAt": "2021-04-21T15:12:51.894Z"
}
],
"createdAt": "2021-04-21T16:19:06.056Z",
"updatedAt": "2021-04-21T16:19:06.056Z",
"__v": 0
}
** Issue with Cart Deletion **
Below is the code I have implemented for this process.
Any suggestions or guidance would be highly appreciated
router.post('/', [isAuthenticated], async (req, res, next) => {
try {
const cart = await CartModel.findOne({ userId: req.user }).populate({
path: 'productsQuantity.productId',
select: {
price: 1,
brand: 1,
productName: 1,
productRef: 1,
pictures: 1
}
});
const prevProductsQuantity = cart
.get('productsQuantity')
.map((el) => el.toObject());
const totalPriceByProduct = prevProductsQuantity.map(
(product) => product.productId.price * product.quantity
);
const totalPrice = totalPriceByProduct.reduce(function (a, b) {
return a + b;
});
const result = await OrderModel.create({
userId: req.user,
totalPrice: totalPrice,
state: 'pending-payment',
productsQuantity: prevProductsQuantity
});
const cartClear = (id) =>
CartModel.deleteOne({
_id: id._id
});
res.status(200).json({
success: true,
data: result
});
cartClear(`${cart._id.toString()}`);
} catch (error) {
next(error);
}
});