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'
})
}));
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());
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
})
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With