Erik
Erik

Reputation: 14770

How to use node-mongodb-connection for connect-mongo

I make connection to my database like the following:

var mongoClient = new MongoClient(new Server('localhost', 27017, {auto_reconnect: true}));
mongoClient.open(function (err, mongoClient) {
  var db = mongoClient.db('db_name');
  db.authenticate('user', 'password', function () {err, result} {
     if (err || !result) return console.log('error');

     app.use(express.session({       
        store: new MongoStore({
          db: db
        })
     });
  });
}); 

And I want to share db connection with MongoStore but it's seem not work. How should I do that?

EDIT: I'm using authentication on my database but after new MongoStore() get executes I'm getting the following error:

not authorized for query on site.system.indexes

Upvotes: 2

Views: 1911

Answers (1)

khurrum qureshi
khurrum qureshi

Reputation: 925

This is how it works for me,

var connectionString = "mongodb://username:password@localhost:27017/db_name";
var dbOptions = {
server:{
    'auto_reconnect': true,
    'poolSize': 20,
    socketOptions: {keepAlive: 1}  
    }
}
// For long running applictions it is often prudent to enable keepAlive. Without it,
// after some period of time you may start to see "connection closed" errors for what 
// seems like no reason.
MongoClient.connect(connectionString, dbOptions, function(err, db) {
    if(err){
        console.log(err);            
    }

app.use(express.session({
        store:new mongoStore({db: db}),
        secret: 'secret'
    }));
})

This works perfectly for me and it will not give you not authorized issues as well. Previously we don't need to give keepAlive option and it works perfectly witout it but with a release of mongodb 2.4 for long running applications we need to give keepAlive option otherwise we keep getting connection closed or not authorized sort of errors.

Upvotes: 5

Related Questions