Req.session array can only store one element at a time

Issue

I am trying to implement a shopping cart functionality in my Express/MongoDB e-commerce app. I create an object to add to the cart by pulling quantity and size (it’s a sneaker store) from the req.body and the itemId from req.session (that I previously saved there upon loading the product page). I am using connect-mongo for my session store.

I would like to store all of the objects added to cart in the cart array in req.session. I came up with this:

router.post('/cart', isLoggedIn, async(req, res) => {
const { itemId } = req.session
const { qty, size } = req.body;
const item = await Item.findById(itemId);
const price = item.price;

const cartItem = {
    itemId: itemId,
    qty: qty,
    size: size,
    price: price,
};

// Add item to cart

req.session.cart = [];
req.session.cart.push(cartItem);

// Calculate totals

req.session.total += price * qty;

req.session.save(err => {
    if(err){
        console.log(err);
        req.flash('error', 'Sorry, something went wrong. :(')
    } else {
        req.flash('success', 'Successfully added to cart.')
        res.send(req.session);
    }
});
})

The object is how I would like it, but the issue is that I can only store one object in the array. Each time I add a new item, it overrides the previous one and I end up with an array of one object.

I was thinking that perhaps I should set the cart attribute to req.session somewhere else before this code runs but can’t figure out how or where to do that. I tried doing it like this in my index.js file:

app.use((req, res, next) => {
    res.locals.session = req.session;
    req.session.cart = [];
    next();
})

But then the array is always empty and nothing is added to it when I call the push method on the post route.

Any ideas on how to fix this would be greatly appreciated.

Solution

You should initialize the array just once:

app.use((req, res, next) => {
    res.locals.session = req.session;
    if (! Array.isArray(req.session.cart)) {
      req.session.cart = [];
    }
    next();
})

Answered By – robertklep

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published