here is a simple connection to use express session store, it keeps banging out this error even though the text is right from the book. I am pretty sure is has something to do with 'new MongoStore' object initialization.
var express = require('express'),
expressSession = require('express-session');
var MongoStore = require('connect-mongo/es5')(expressSession);
var sessionStore = new MongoStore({
host: '127.0.0.1',
port: '27017',
db: 'session'
});
var app = express()
.use(expressSession({
secret: 'my secret sign key',
store: sessionStore
}))
.use('/home', function (req, res) {
if (req.session.views) {
req.session.views++;
}
else {
req.session.views = 1;
}
res.end('Total views for you:' + req.session.views);
})
.use('/reset', function(req, res) {
delete req.session.views;
res.end('Cleared all your views');
})
.listen(3000);
Add URL to new MongoStore()
var sessionStore = new MongoStore({
host: '127.0.0.1',
port: '27017',
db: 'session',
url: 'mongodb://localhost:27017/demo'
});
The code in the question is from the book Beginning Node.js by Basarat Ali Syed.
You need to define a database connection and then pass it to the new MongoStore. The 'db:' parameter you are using is expecting a MongoDB driver connect, not a url to a Mongo Database. For that, you should do something like this:
var sessionStore = new MongoStore({ url:'mongodb://localhost:27017/test');
Here's an example I know works, although it uses Mongoose instead of the MongoDB driver.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var sessionStore = new MongoStore({mongooseConnection: mongoose.connection });
Check the section Using Other Connect-Compatible Session Stores in http://sailsjs.com/documentation/reference/configuration/sails-config-session.
There are version restrictions regard the connect-mongo module and the example shows a different set of parameters than the ones in the documentation:
// Note: user, pass and port are optional
adapter: 'connect-mongo',
url: 'mongodb://user:pass@host:port/database',
collection: 'sessions',
auto_reconnect: false,
ssl: false,
stringify: true
I actually only had to use:
// Note: user, pass and port are optional
adapter: 'connect-mongo',
url: 'mongodb://localhost:27017/sails',
collection: 'sessions'
Hope it helps!
Since you're using a session collection so it should be like this
app.use(expressSession({
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'session',
})
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With