Search code examples
mongodbexpressmongoose

How to set up connect-mongo (or use sessions in mongoose)


I am using ExpressJS and Mongoose.

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

app.use(express.session({ secret: "myappsecret", store:sessionStore }));

This results in an "MongoError: Error: unauthorized db". I suppose I would need to pass it my log-in credentials. I also have,

var mongoose = require('mongoose');
var db = mongoose.createConnection('<omitted username, password and address>', 'myappsession');

I am guessing connect-mongo needs this information to log into my database to create the session store?

How do I pass connect-mongo the log-in information? Or am I doing this wrongly?


Solution

  • In my case, since I am already actively using Mongoose, I ended up using a solution for Mongoose.

    1. Install session-mongoose

    https://github.com/donpark/session-mongoose

    2. Use this tutorial as a guide.

    http://mikevalstar.com/Blog/107/Coding_with_Nodejs_Part_31_Mongoose_Sessions

    3. In particular, I had problem with this line of the tutorial.

    url: "mongodb://localhost/mv"
    

    This should be something like,

    url: "username:password@url/testdatabase"
    

    Sessions are then stored in the database named ""testdatabase" in the collection "sessions".

    I hope this answer help someone avoid some frustration. :)