Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store session values with Node.js and mongodb?

How do I get sessions working with Node.js, [email protected] and mongodb? I'm now trying to use connect-mongo like this:

var config = require('../config'),
    express = require('express'),
    MongoStore = require('connect-mongo'),
    server = express.createServer();

server.configure(function() {
    server.use(express.logger());
    server.use(express.methodOverride());
    server.use(express.static(config.staticPath));
    server.use(express.bodyParser());
    server.use(express.cookieParser());
    server.use(express.session({
        store: new MongoStore({
            db: config.db
        }),
        secret: config.salt
    }));
});

server.configure('development', function() {
    server.use(express.errorHandler({
        dumpExceptions: true,
        showStack: true
    }));
});

server.configure('production', function() {
    server.use(express.errorHandler());
});

server.set('views', __dirname + '/../views');
server.set('view engine', 'jade');

server.listen(config.port);

I'm then, in a server.get callback trying to use

req.session.test = 'hello';

to store that value in the session, but it's not stored between the requests.

It probobly takes something more that this to store session values, how? Is there a better documented module than connect-mongo?

like image 614
tirithen Avatar asked Mar 19 '11 19:03

tirithen


People also ask

How does node js display data from MongoDB?

To select data from a collection in MongoDB, we can use the findOne() method. The findOne() method returns the first occurrence in the selection. The first parameter of the findOne() method is a query object.

Where is session stored in node JS?

The session is stored in the express server itself. The default server-side session storage, MemoryStore , is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.


2 Answers

Take a look at this series from DailyJS. It uses MongoDB and session management

http://dailyjs.com/tags.html#lmawa

like image 173
johans Avatar answered Oct 18 '22 02:10

johans


I am not experienced with Node.js or Express, so I cannot immediately see what's wrong with your approach. However, I have made Express use MongoDB to store sessions for flash messages and other session stuff.

You can see my source code for a simple URL shortener here (that actually makes the URLs pretty long at the moment - it was just an exercise ;)). I use the session to store a list of URLs that the current user has shortened.

It is not pretty, but I know it works.

like image 39
mookid8000 Avatar answered Oct 18 '22 02:10

mookid8000