How to find a session from MongoDB collection using Express and MongoStore How to find a session from MongoDB collection using Express and MongoStore mongodb mongodb

How to find a session from MongoDB collection using Express and MongoStore


When you use MongoStore for storing your session data you don't need to query the MongoDB directly. The module does everything for you.

You can just use req.session to get your session data.

So in your routes you can do something like:

app.get('/', function(req, res){  // check if the username is set in the session  if (!req.session.username) {    // redirect it to login page    res.redirect('/login');  } else {    // do something  }});app.post('/login', function(req, res) {    // you would check check the username & password here    // if (username == '...' /&& password ...)    // set the username in the session session     req.session.username = username; });