Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't store session in MongoDB with passport

I'm new to Node JS and I'm trying to store session in mongoDB by using the connect-mongo npm package , once I add the following line - i get an error :

app.use(session({
  saveUninitialized: true,
  resave: true,
  store   : new MongoStore({ // adding this will cause an error
  db: 'users'
 })
}));

Error

Here are the session parts of my code (i'm using express 4.16) :

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var session = require('express-session');
    var passport = require('passport');
    var LocalStrategy = require('passport-local').Strategy;
    var expressValidator = require('express-validator');
    var multer = require('multer');
    var upload = multer({dest: './uploads'});
    var flash = require('connect-flash');
    var bcrypt = require('bcryptjs');
    var mongo = require('mongodb');
    var mongoose = require('mongoose');
    var MongoStore  = require('connect-mongo')(session);
    var db = mongoose.connection;
    session(app, mongo.initSessionStore);

   app.use(session({
      saveUninitialized: true,
      resave: true,
      store   : new MongoStore({
        db: 'users'
      })
    }));

    // Passport
    app.use(passport.initialize());
    app.use(passport.session());
like image 428
RoyBarOn Avatar asked Oct 08 '17 16:10

RoyBarOn


1 Answers

You haven't sent instance of MonogDB to MongoStore. You sent string 'user', and it expect database instance. So it can't connect to MonogDB.

If you are using Mongoose you need first to connect to database, and then you can usemongoose.connection for MongoStore:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

app.use(session({
      saveUninitialized: true,
      resave: true,
      store   : new MongoStore({
        mongooseConnection: db
      })
}));
like image 80
Ivan Vasiljevic Avatar answered Nov 10 '22 04:11

Ivan Vasiljevic