从sessionStore检索会话列表并销毁用户以前的会话NodeJS

时间:2016-11-22 11:15:57

标签: node.js session mongoose meanjs express-session

我需要从sessionStore(MongoStore)检索列表会话并删除以前的登录会话。我正在使用快速会话在DB中存储会话。

var userId = req.query.userid;
  if (!userId)
    return res.status(400).send({
      message: errorHandler.getErrorMessage('No user found in input request')
    });

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

  sessionsColl.find({
    'session.passport.user': userId,
    '_id': { '$ne': req.sessionID }
  }, function (err, userSessions) {
    console.log(userSessions);
    if (userSessions !== null && typeof userSessions._id !== 'undefined') {
      store.destroy(userSessions._id, function (err, dat) {
        console.log(dat);
      });      
    }
  });

但是在 userSessions 对象中我得到的是一个对象而不是集合,我无法理解如何从 userSessions 对象中获取会话列表

userSessions object response

2 个答案:

答案 0 :(得分:2)

最后,我可以解决这个问题 这是我的代码

    exports.logoutFromPreviousDevices = function (req, res) {
  var userId = req.query.userid;
  if (!userId)
    return res.status(400).send({
      message: errorHandler.getErrorMessage('No user found in input request')
    });

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

  sessionsColl.find({
    // 'session.passport.user': userId,
    // we are tryin to remove all sessions, you can leave current
    // '_id': { '$ne': req.sessionID }
  }, function (err, userSessions) {
    if (userSessions !== null) {
      userSessions.toArray(function (a, sessionsData) {
        sessionsData.forEach(function (element, index) {
          var data = JSON.parse(element.session);
          if (element._id !== req.sessionID && req.query.userid === data.passport.user) {
            store.destroy(element._id, function (destroyerr, dat) {
              if (destroyerr)
                return res.status(400).send({
                  message: errorHandler.getErrorMessage(destroyerr)
                });
              res.jsonp({ status: 'Previous session deleted' });
            });
          }
        });
      });
    } else {
      res.jsonp({ status: 'No session found' });
    }
  });
};

答案 1 :(得分:0)

下面的代码解决了我的问题。

var store = req.sessionStore;    
for(var sid in store.sessions){ 
    var ses = JSON.parse(store.sessions[sid]);    
    if(ses.passport.user.username==core_id) {         
        store.destroy(sid, function (err, dat) {                    
        });       
    }
}