0

i am trying to create session with mongodb in node.js already i have a connection like this

var Db=require('mongodb').Db;


var BSON=require('mongodb').BSONPure;

var Server=require('mongodb').Server;


 var client=new Db('db',new Server('localhost', 27017), {safe:false});

and then i have tried to configure session like this

 app.use(express.session({

   store: new mongoStore({ db: client }),
    secret: 'topsecret'

   }));

i ran the server.js file i got this error mongoStore undefined so to resolve this error i have added this

  var mongoStore= require('connect-mongodb');

again i ran it i did't get any error but i got below error when i tried to find or save data into db

    Cannot call method 'findOne' of undefined

how to resolve this problem and how to create session with mongodb in node.js

1 Answer 1

3

Here's a very simple setup:

var express     = require('express');
var MongoStore  = require('connect-mongo')(express);
var app         = express();

app.use(express.cookieParser()); // required to handle session cookies!
app.use(express.session({
  secret  : 'YOUR_SESSION_SECRET',
  cookie  : {
    maxAge  : 10000              // expire the session(-cookie) after 10 seconds
  },
  store   : new MongoStore({
    db: 'sessionstore'
    // see https://github.com/kcbanner/connect-mongo#options for more options
  })
}));

app.get('/', function(req, res) {
  var previous      = req.session.value || 0;
  req.session.value = previous + 1;
  res.send('<h1>Previous value: ' + previous + '</h1>');
});

app.listen(3012);

If you run it and open http://localhost:3012/ in your browser, it will increase the value by 1 each time you reload. After 10 seconds, the session will expire and the value will be reset to 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.