learner learner - 6 months ago 48
Node.js Question

Node.js updating session field

In my

req.session.cart
I have numbers of object. I want to update the quantity field whenever the particular is passed as query parameter. I tried but I'm only able to append another quantity field instead of updating it.

[
{
"_id": "573e8cb8d41066b112908598",
"quantity": 1
},
{
"_id": "573e8c6ad41066b112908597",

"quantity": 1
}
]


this is what I tried

function processEdit(req, res, next) {
var quantity = req.body.quantity;
req.session.cart.forEach(function(data) {
if (data._id == req.params._id) {
arrayTrue = false;
}
});
if (arrayTrue) {
req.session.cart.quantity = quantity;
console.log(req.session.cart);
}
res.send(req.session.cart);

Answer

Your cart is an array.

req.session.cart[index].quantity++ if you have an index.

And if you have an id:

req.session.cart.forEach(item => {
  if (item._id == id) {
     item.quantity++;
  }
});
Comments