I am trying to update my stock in the MongoDB database. After Every purchase one stock item will be subtracted. Update multiple ids in the API that subtract the available amount from the database.
This is the handler code:
const { _id, availableQty } = req.body;
console.log(req.body);
for (let i = 0; i < req.body.length; i++) {
const doc = await Product.updateOne(
{ _id },
{
availableQty,
}
);
console.log(doc);
}
return res.json(true);
This is the Axios call. This Info below is also a response from an API
let info = res.data;
const items = info.line_items;
items.forEach(productInfo);
function productInfo() {
let p_id = items.map((p) => ({
_id: p.product_id,
availableQty: p.product_qty - 1,
}));
axios
.put( /api/products/updateproducts , p_id)
.then((res) => {
console.log(res.data);
})
.catch((res) => {
console.log(res);
});
}
This is the console.log of res.body in API handler:
[
{ _id: 646e4ff2707bca32ac9c9a00 , availableQty: 6 },
{ _id: 646e4fe4707bca32ac9c99ff , availableQty: 6 },
{ _id: 646e4fd4707bca32ac9c99fe , availableQty: 6 },
{ _id: 646e4fc9707bca32ac9c99fd , availableQty: 6 }
]
[
{ _id: 646e4ff2707bca32ac9c9a00 , availableQty: 6 },
{ _id: 646e4fe4707bca32ac9c99ff , availableQty: 6 },
{ _id: 646e4fd4707bca32ac9c99fe , availableQty: 6 },
{ _id: 646e4fc9707bca32ac9c99fd , availableQty: 6 }
]
[
{ _id: 646e4ff2707bca32ac9c9a00 , availableQty: 6 },
{ _id: 646e4fe4707bca32ac9c99ff , availableQty: 6 },
{ _id: 646e4fd4707bca32ac9c99fe , availableQty: 6 },
{ _id: 646e4fc9707bca32ac9c99fd , availableQty: 6 }
]
[
{ _id: 646e4ff2707bca32ac9c9a00 , availableQty: 6 },
{ _id: 646e4fe4707bca32ac9c99ff , availableQty: 6 },
{ _id: 646e4fd4707bca32ac9c99fe , availableQty: 6 },
{ _id: 646e4fc9707bca32ac9c99fd , availableQty: 6 }
]