简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM