Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Question

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

like image 926
Legendre Avatar asked Oct 06 '22 13:10

Legendre


1 Answers

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. :)

like image 181
Legendre Avatar answered Oct 09 '22 03:10

Legendre