Search code examples
node.jsmongodbexpress-session

express-session entry not completely removed from mongodb


I am using express-session along with connect-mongodb-session packages in a nodeJS app to store sessions in mongodb database.

Problem

When I try to delete a session saved in the database using req.session.destroy() function, it removes user-related information from the session entry saved in a database but it doesn't remove the session entry completely from the database.

Question

How can i fix this problem? Why is session entry completely removed from the database?

Code

const expressSession = require('express-session');
const MongoDbStore = require('connect-mongodb-session')(expressSession);

const sessionStore = new MongoDbStore({
    uri: dbConnectionStr,
    collection: 'sessions'
});

app.use(expressSession({
    secret: 'sessionsecret',
    resave: false,
    saveUninitialized: false,
    store: sessionStore
}));

code where req.session.destroy is called

const logout = (req, res) => {
    try {

         // destroy session saved in db
            req.session.destroy((error) => {
            if (error) {
                throw new Error('something went wrong while logging out')
            }
            res.redirect('/login');
        });

    } catch (error) {
        res.status(400).send(utils.standardResponse('error', error.message));
    }
};

Solution

  • For anyone else who might encounter this problem, here's the solution

    when setting up express-session, set the unset option to destroy

    app.use(session({
        secret: process.env.EXPRESS_SESSION_SECRET,
        resave: false,
        saveUninitialized: false,
        store: sessionStore,
        unset: 'destroy'                   <-------- 
    }));
    

    then in your route handler whenever you want to destroy the session entry in session store, just set req.session to null

    const logout = (req, res) => {
        req.session = null;   
        res.redirect('/login');
    };