node.jsmongodbexpressconnect-mongo

How do I reload a session based on sid? (expressjs and connect-mongo)


I am building a restful api for my mongo database and I am trying to reload a users session based on the SID sent via the api call. I have my server serving up sessions fine, but I can't for the life of me figure out how to reload a session into req.session through connect-mongo and have it saved again (based on original sid) once the request is sent out.

Anything I saved to the req.session gets put into a completely new session, and doesn't write to my previous session data.

I have no trouble writing something to save my session data pulled from the database but i figured there was a way to have to have it automactially handled by expressjs or connect-mongo.


Solution

  • I ended up solving my issue, though I think a lot of my headaches related to my poor understanding on how sessions should be handled. Although its not what i ultimately wanted, it ended up giving me essentially the same result.

    Looking over Patrick's code got me thinking that is was probably some sort of scoping/binding issue. With a couple of tweaks I was finally able to access the connect-mongo prototyped functions by creating my mongoStore Obj outside of the express session then passing that obj into express.session.

    MongoStore = require('connect-mongo')
    var mongoSession = new MongoStore(conf.db);
    
    //Configure Session Db
    var conf = {
      db: {
        db: 'sessions',
        host: '127.0.0.1',
      },
      secret: 'kittens'
    };
    
    app.configure(function(){
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');      
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(express.cookieParser());
      app.use(express.session({
        secret: conf.secret,
        maxAge: new Date(Date.now() + 3600000),
        store: mongoSession
      }));
      app.use(allowCrossDomain);
      app.use(require('stylus').middleware({ src: __dirname + '/public' }));
      app.use(app.router);
      app.use(express.static(__dirname + '/public'));
    
    
    });
    

    Now i was able to easily get/set previous sessions through the mongostore obj. I know there are probably other ways to go about doing the same thing, (ie access mongodb directly) though I wanted to see what was possible simply with the mongostore obj itself.

    Also thanks for the thoughts on this Patrick, definitely helped me think in the right direction.

    Hope this helps someone!