Zaid Iqbal Zaid Iqbal - 5 months ago 32
Node.js Question

Delete previous sessions if login from new device MEANJS

I want to remove previous session from MongoStore/sessionStore if a user login from new device. MEANJS is using


to store sessions in mongodb. I did search on it but could not find a solution to fetch the list of sessions from db. Please help me here

MongoStore = require('connect-mongo')(session),
favicon = require('serve-favicon'),

module.exports.initSession = function (app, db) {
// Express MongoDB session storage
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
cookie: {
maxAge: config.sessionCookie.maxAge,
httpOnly: config.sessionCookie.httpOnly,
secure: &&
key: config.sessionKey,
store: new MongoStore({
mongooseConnection: db.connection,
collection: config.sessionCollection


This should work, at least it's a good starting point for you

var async = require('async'); //npm install async --save
exports.removeSessionsForUser = function(req, res, next) {
    var userId = req.user ? : undefined;
    if (!userId)
        return next(new Error('No user found in req. Exiting'));

    var store = req.sessionStore;
    var sessionsColl = store.db.collection('sessions');

        'session.user': userId,
        // we are tryin to remove all sessions, you can leave current
        // '_id': { '$ne': req.sessionID }
    }, { _id : 1 }, function (err, userSessions) {
        async.each(userSessions, function (userSession, cb) {
            store.destroy(userSession._id, cb);
        }, function(notDone) {
                return next(new Error(notDone));


This uses async.each, which is

async.each(Array, function(item, callback) {/* iterate */}, function(error) {/* end */});