0
// server.js

// set up ======================================================================
// get all the tools we need
var express  = require('express');
var app      = express();
var port     = process.env.PORT || 8080;
var mongoose = require('mongoose');
var path = require('path');
var bodyParser   = require('body-parser');
var credentials = require('./credentials.js');
var session = require('express-session');


// set up handlebars view engine
app.set('views',path.join(__dirname,'public/views'));
app.set('view engine', 'hbs');    

// setup
app.use(express.static(path.join(__dirname, 'public/assets')));

//db config
var configDB = require('./config/db.js');
mongoose.connect(configDB.url); // connect to our database


//mongoose session setup
const MongoStore = require('connect-mongo')(session);
var options = {
    server: {
        socketOptions: { keepAlive: 1 }
    }
};

//body parser and session and cookie parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('express-session')({
    resave: false,
    saveUninitialized: false,
    secret: 'iamsupersecret',
    store: new MongoStore({url:configDB.url,options})
}));

// flash message middleware
app.use(function(req, res, next)
{
    res.locals.flash = req.session.flash;
    delete req.session.flash;
    next();
});


// routes ======================================================================
require('./routes.js')(app);

// 404 catch-all handler (middleware)
app.use(function(req, res, next)
{
    res.status(404);
    res.render('404');
});

// 500 error handler (middleware)
app.use(function(err, req, res, next)
{
    console.error(err.stack);
    res.status(500);
    res.render('500');
});



// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);

I am building a small app for buying tickets, for now i have a cart collection in my mongodb that saves the users cart using the session id. I want to instead save the data in a session-like manner, so that as soon as the user ends the session the cart is deleted and i won't need the database anymore because i do not need the carts data as i have a sales data for all the logistics i need. below is my cart controller showing how i currently save data to my cart collection.

exports.addItem = function (req, res)
{
    if(!userKey)
    {
        userKey = req.session.id;
    }

    Cart.findOne({userKey : userKey},function (err, cart)
    {
        if(err)
        {
            console.log("Error finding cart "+err);
            req.session.flash =
            {
                type: 'danger',
                intro: 'Ooops!',
                message: 'There was an error finding your cart.'
            };
            return res.redirect(303, '/cart');
        }
        else if(!cart)
        {
            cart = new Cart();
            cart.userKey = userKey;
            cart.items = [];

            Ticket.findOne({_id:req.params.id},function (err, ticket)
            {
                if(err)
                {
                    console.log("Error finding ticket "+err);
                    req.session.flash =
                    {
                        type: 'danger',
                        intro: 'Ooops!',
                        message: 'There was an error finding that ticket.'
                    };
                    return res.redirect(303, '/cart');
                }

                var item = {
                    id:ticket._id,
                    type: ticket.type,
                    price: ticket.price,
                    quantity: 1,
                    time: ticket.time,
                    date: ticket.date
                };
                cart.items.push(item);
                cart.save();
                return res.redirect(303,'/cart');

            });
        }
        else if(cart)
        {
            Ticket.findOne({_id:req.params.id},function (err, ticket)
            {
                if (err)
                {
                    console.log("Error finding ticket "+err);
                    req.session.flash =
                    {
                        type: 'danger',
                        intro: 'Ooops!',
                        message: 'There was an error finding that ticket.'
                    };
                    return res.redirect(303, '/cart');
                }

                else
                {
                    var item =
                    {
                        id:ticket._id,
                        type: ticket.type,
                        price: ticket.price,
                        quantity: 1,
                        time: ticket.time,
                        date: ticket.date
                    };
                    cart.items.push(item);
                    cart.save();
                    return res.redirect(303,'/cart');
                }


            });
        }
    });
};
lagfvu
  • 597
  • 6
  • 21

1 Answers1

0

as explain in this answer try to link it with cookies

app.use(express.session({cookie: { path: '/', httpOnly: true, maxAge: null}, secret:'eeuqram'}));

maxAge: null will make sure that session expires after browser is closed.

Community
  • 1
  • 1
enRaiser
  • 2,606
  • 2
  • 21
  • 39