I am currently working on a basic app that allows logged in users to search and book train journeys using Express, MongoDB, Mongoose, and Express-session. The selected journeys are temporarily stored in the req.session.order variable (which I believe is global across all routes). Once the user confirms the booking, the selected journeys are saved as sub-documents of the user in the database. The issue I'm facing is that even after confirmation, when returning to the home page, the req.session.order array still contains previously booked journeys.
After reviewing the code below, it seems that the req.session.order array is properly cleared at the end of the /confirm route instruction. However, upon navigating back to the home page, the console continues to display previously pushed journey ids.
I suspect there may be an issue with how express-session is being utilized. Any assistance you can provide will be greatly appreciated.
// (req.session.order is initialized to [] in signin/signup routes before redirecting to the home page)
/* GET confirmation page. */
router.get('/order', async function(req, res, next) {
var bookedJourney = await journeyModel.findOne({ _id: req.query.id });
**req.session.order.push(bookedJourney);**
res.render('confirmation', {order: req.session.order, reformatTime: reformatTime, reformatDate: reformatDate});
});
/* POST add selected journeys to trip list */
router.post('/confirm', async function(req, res, next) {
var currentUser = await userModel.findOne({ email: req.session.user.email });
req.session.order.forEach((order) => {
currentUser.journey.push(order._id);
});
await currentUser.save();
**req.session.order = []; // This successfully clears the array as expected**
console.log(req.session.order);
});
In the HTML, when clicking on the confirm button, a modal is launched with a button leading back to the home page:
/* GET home page. */
router.get('/home', function(req, res, next) {
**console.log(req.session.order); // Not sure why req.session.order here still has the bookedJourney id, it should be empty []**
if (!req.session.user) {
res.redirect("/");
} else {
console.log(req.session.order); // Ditto
res.render('home', { user: req.session.user });
}
});