Pio
Pio

Reputation: 4062

How to set up Mongoose and connect-mongo?

I had an Error setting TTL error when starting my application in Express. Maybe the problem is because I use for sessions and for DB operations the same database through different connections.

So it there a specific sequence of requiring connect-mongo and mongoose that needs to be respected if I want to store my sessions in MongoDB via the connect-mongo middleware and use Mongo as my database for my app-specific data?

Currently my app looks like this:

App.app.use(express.session({
store: new MongoStore({
    db: settings.cookie.db,
    host: settings.cookie.host,
    port: settings.cookie.port
}),
    secret: settings.cookie.secret
}))

and later I set start the connection for Mongo:

 function connect(connectionString) {
     mongoose.connect(connectionString)

     var db = mongoose.connection
     db.on('error', console.error.bind(console, 'connection error'))
     db.once('open', function callbck() {
        console.log('Mongoose connected at: ', connectionString)
       })
     } 

There are no error logs apart.

Also how do I tear down properly Mongo connections when I close my app (from command line let's say)? For this question I found the answer here I think.

Upvotes: 1

Views: 3400

Answers (1)

Artsiom Anti-Flag
Artsiom Anti-Flag

Reputation: 71

First of all i've created a sessionStore module

var mongoose = require('mongoose'),
express = require('express'),
MongoStore = require('connect-mongo')(express),
sessionStore = new MongoStore({mongoose_connection: mongoose.connection});
module.exports = sessionStore;

Then i've included it into app

sessionStore = require('libs/sessionStore');

And finaly

app.use(express.session({
  secret: config.get('session:secret'),
  key: config.get('session:key'),
  cookie: config.get('session:cookie'),
  store: sessionStore
}));

That's config

"session": {
    "secret": "secret",
    "key": "connect.sid",
    "cookie": {
        "path": "/",
        "httpOnly": true,
        "maxAge": null
    }
},

Upvotes: 6

Related Questions