Day 72, how to store express.js session in mongodb

There are many ways to store sessions in Express.js, including:
– Memory
– Traditional database
– In memory database

Our group project is using MongoDb to store session. The code is:

  var express = require('express');
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://myuser:mypass@localhost:27017/mydb');
  var MongoStore = require('connect-mongo')(express);
  app.use(express.session({
    store: mongoStore(new MongoStore({ db: mongoose.connection.db })),
    secret:"changeme"
  }));

If we are going to use Redis, the code would look like(?):

var RedisStore = require('connect-redis')(express);
app.use(express.session({
  store: new RedisStore({host: 'localhost', port: 3000, client: redis}),
  secret: "changeme"
}));

Do we have to turn on cookie to support session? The answer must be yes.
A good article to read: http://stackoverflow.com/questions/5522020/how-do-sessions-work-in-express-with-nodejs/11585839#11585839


// pass a secret to cookieParser() for signed cookies
app.use(express.cookieParser('manny is cool'));

// add req.session cookie support
app.use(express.cookieSession());
Advertisements
Standard