简体   繁体   中英

how to create session using mongodb in node.js

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

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.

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