简体   繁体   中英

connect-mongo clarification needed, how to use it for sessions with express in nodejs

In my node.js app, I'm trying to get the session data to store in a mongoDB database.

But the usage of connect-mongo is somewhat puzzling to me and I was hoping if someone could explain to me the correct usage, along with all the other usages referenced below.

This tutorial http://blog.modulus.io/nodejs-and-express-sessions tells it to use it like this

var express = require('express');
var app = express();
var MongoStore = require('connect-mongo')(express);

app.use(express.cookieParser());
app.use(express.session({
  store: new MongoStore({
    url: 'mongodb://root:myPassword@mongo.onmodulus.net:27017/3xam9l3'
  }),
  secret: '1234567890QWERTY'
}));

//...

But the main plugin site uses it like this

var express = require('express');
var MongoStore = require('connect-mongo')(express);

app.use(express.session({
    secret: settings.cookie_secret,
    store: new MongoStore({
      db: settings.db
    })
  }));

It's using the store differently..

However, I have had used this in the past, and although I can't get it working now, I used it somewhat like this

var SessionStore = require('connect-mongo')(express); 
// not sure exactly what was assigned, but this same variable name was used below..

app.configure(function() {
     ...
     app.use(express.session({
         secret: secretSauce,
         store: SessionStore, // < ..here
     }));
     ...
 });

My old way seemed more elegant to me but it's not working as it is. And I can't make much sense of what's going on in the first two examples and why are they so different. Can someone explain what I need to do from those two to arrive at mine?

This got it working

var MongoStore = require('connect-mongo')(express);
var SessionStore = new MongoStore({
    db: 'SessionStore'
});

app.use(express.session({
    secret: secretSauce,
    store: SessionStore,
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM