How to Set Cookies and Session in MongoDB

In my NodeJS project, I use the MongoDB database. There is various type of professing to set session and cookies in your project. I am using a 32bit OS where I don't have any mongo campus, that's why if I try to check my database writing a query is the only process to show my database and also the collection. When you set your session on your project sessions collection is automatically created in your database. Where your all session data is stored and also you have to clear your cookies.

In my project I install two npm package "cookie-parser" and "express-session" and I define the packages in app.js like:

var cookieParser = require('cookie-parser');
var session = require('express-session');

Also I install two more packages "connect-mongo" and "mongoose" and define like this:

var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

Now I use session in app.js. Below is the code for your reference:

app.use(session({
    secret: 'botnyuserdetails',
    resave: true,
    saveUninitialized: true,
    cookie: { maxAge: 365 * 24 * 60 * 60 * 1000 },
    store: new MongoStore({
      mongooseConnection: db,    
      host: '127.0.0.1', 
      port: '27017', 
      collections: 'sessions', 
      url: 'mongodb://localhost:27017/yourProjectName'    
    })
  }));

  app.use((req, res, next) => {
    if (req.cookies.user_sid && !req.session.user) {
        res.clearCookie('user_sid');        
    }
    next();
});

Conclusion:

Now you go and check your database collections where session collection is created. Now for user authentication, you can use the session as user validation.

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.