mongo-connect error with mongo-connect(session) - node.js

After searching around about it, I can't find any solution or mistake in my code about this error. I've got my app.js files inside my node JS application with the mongo-connect declaration :
const MongoStore = require('connect-mongo')(session)
And I've got this error :
TypeError: Class constructor MongoStore cannot be invoked without
'new'
at Object. (/Users/souhailmohamed/project/devops/story website/app.js:11:20)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
There is my app.use code beloww :
app.use(session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}))
I understand pretty well about the
const MongoStore = require('connect-mongo')(session)
but I didn't understand the error. But it's from a tutorial from youtube by traversy media LinK

connect-mongo v4 introduces new signature (compared to v3).
Here is the official migration guide.
Also, here is a quick diff of what I changed in my specific project (using mongoose and dotenv) to upgrade from connect-mongo v3 to v4:

I had the same problem in my code and solved it using this:
const MongoDbStore = require('connect-mongo');
Remove (session) from the require statement and update the app.use() like this:
// Session Config
app.use(
session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: MongoDbStore.create({
mongoUrl: YourDatabaseURL
})
})
);

I was following the same so I discovered an npm pakage connect-mongodb-session.
Install it and use the same code of session as Brad uses in his video
const MongoDBStore = require('connect-mongodb-session')(session);
//sessions
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUnitialized: false,
store: new MongoDBStore({
mongooseConnection: mongoose.connection
})
//cookie: { secure: true }
}))
const store = new MongoStore({
uri: 'your mongo uri' ,
collection:'mySessions'
})
//express middleware
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: store
// Don't create a session until something is stored
// cookie: { secure: true } - this wont work without https
}))
It solved my relogging issue also. If you close the tab and renter to localhost you get yourself logged in already

Ok so i've found a way to resolve it, i don't about the reason, on which version of express to use but i removed the (session) after mongo-connect and change the app.use to this :
app.use(session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: 'mongodb+srv://<id+ password>#cluster0.cq7f2.mongodb.net/DBname?retryWrites=true&w=majority' })
}))

Certain rule are changed for the syntax in "connect-mongo" document here
const MongoStore = require("connect-mongo");
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI //(URI FROM.env file)
})
//stroed it in database
}));

In your app.js make the following changes:
let MongoStore = require('connect-mongo');
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: 'your mongo url'
})
});
);
References:
https://www.npmjs.com/package/connect-mongo

It seems that 'connect-mongo' is obsolete and the newer version includes 'connect-mongodb-session'
const MongoDBStore = require('connect-mongodb-session')(session);
Use the above code instead and it should work without any errors.
Note: install the 'connect-mongodb-session' package using npm init connect-mongodb-session

I have same problem. Here is the solution:
var session = require('express-session');
var MongoStore = require('connect-mongo');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
app.use(session({
secret : 'mysecretkey',
resave : true,
saveUninitialized : true,
store :MongoStore.create({ mongoUrl: DBUrl })
}));

app.use(session({
store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));
// Advanced usage
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://user12345:foobar#localhost/test-app?authSource=admin&w=1',
mongoOptions: advancedOptions // See below for details
})
}));

Here is the solution:
const session = require('express-session');
const MongoStore = require('connect-mongo');
const mongoose = require('mongoose');
app.use(session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: new MongoStore({
mongoUrl: mongoose.connection._connectionString,
mongoOptions: {}
})
}))

Just use the another npm package connect-mongodb-session and it should work
https://www.npmjs.com/package/connect-mongodb-session
const MongoDBStore = require('connect-mongodb-session')(session);

Related

MongoStore, Atlasdb return the mongoUrl and ClientPromise

I am getting error while trying to save session on mongodb. Here is my code.
//MIDDLEWARE FUNC
app.use(methodOverride('_method',{methods: ['POST','GET']}))
app.use(Express.static(path.join(__dirname, 'public')))
app.use(Express.urlencoded({extended:true}))
app.use(Express.json())
app.use(session({
secret: 'my_keyboard_cat',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: process.env.DB_URI,
dbName: 'sessions'
})
}))
app.use(flash())
app.use((req,res,next) => {
res.locals.flashMessages = req.flash()
next()
})
and error is : Assertion failed: You must provide either mongoUrl|clientPromise|client in options
/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:119
throw new Error('Cannot init client. Please provide correct options')
Error: Cannot init client. Please provide correct options

Class constructor MongoStore cannot be invoked without 'new' (Express-NodeJs)Backend

I m creating react-auth . Firstly I created server side. I need to connect mongodb but i didnt manage.
const session = require('express-session') const Mongostore = require('connect-mongo')(session)
``const cors = require('cors')
app.use(session({ secret: 'secret',
store: new Mongostore({ mongooseConnection: mongoose.connection
}), resave: true,
saveUninitialized: true }))
For those who want to the latest version of connect-mongo, the new syntax involves removing the parameter session from the require call and not using new any more but a method .create.
Here is what the documentation recommends:
const session = require('express-session');
const MongoStore = require('connect-mongo');
app.use(session({
secret: 'foo',
store: MongoStore.create(options)
}));
Basic usage would be:
app.use(session({
store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));
I had a similar issue while working on replit. My solution was to downgrade connect-mongo's version from 4 to 3.
npm uninstall connect-mongo
npm i connect-mongo#3
From this user's post:
https://forum.freecodecamp.org/t/advanced-node-and-express-error/450979/3
const session=require("express-session");
const MongoStore=require("connect-mongo");
//*****************
app.use(session({
secret:"secret",
cookie:{maxAge:60000},
resave:false,
saveUninitialized:false,
store:MongoStore.create({mongoUrl:process.env.MONGO_URI}),
I also had the same Error, What i did was to npm i connect-mongodb-session
const MongoStore = require('connect-mongodb-session)(session)
I then created a middleware by session
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: process.env.MONGO_URI }),
})
);
Instead of coding my URI directly, i instead loaded it from the .env file with process.env.MONGO_URI
Please make the following changes on your code, from:
const MongoStore = require('connect-mongo')(session);
Use, instead:
const MongoStore = require('connect-mongo')
And in the session object options use:
store: MongoStore.create({ mongoUrl: process.env.CONNECTIONSTRING })
process.env.CONNECTIONSTRING is the link provided by mongodb that you may store in the .env
I tried downgrading the mongo-connect version as suggested above but found it more reliable to keep it up to date with current version and using the new method create with different key name, following the documentation guidelines

Default path for SQLite Store - Node.js

app.use(session({
store: new SQLiteStore,
secret:"xxxxxx",
saveUninitialized: false,
cookie: { maxAge: 60000 },
rolling: true,
resave: true
}));
By default new file with sessions named "sessions" is being created in a root directory. How to change default path?
var session = require('express-session');
var SQLiteStore = require('connect-sqlite3')(session);
app.use(session({
store: new SQLiteStore({dir:'./db/', db: 'sessions'}),
...

req.user undefined in Express 4

I built an app that uses Oauth to authenticate with a third party Jawbone app. I'm attempting to pull req.user.jawbone.token from req.user in one of my routes; however, I'm getting an error stating that req.user is undefined. I had this working in express 3, but after upgrading to express 4 it's no longer working - which leads me to believe that my sessions aren't being stored properly.
Here are the relevant parts of my app.js configuration:
var passport = require('passport');
var session = require('express-session')
var MongoStore = require('connect-mongo')({session: session});
require('./config/passport')(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// passport
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(session({
store: new MongoStore({
url: mongoUrl
}),
secret: 'password',
resave: false,
saveUninitialized: true
}));
For anyone else that runs into this problem, the issue was due to my middleware being in the wrong order. I rearranged to the below and it's working properly
app.use(session({
store: new MongoStore({
url: mongoUrl
}),
secret: 'password',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect giving error in nodejs

I am using node to connect to mongoose database, but when i run the code, it gives error as:
Uncaught TypeError: undefined is not a function
(anonymous function) server.js:13
Below is the code which i am running in server.js
var express= require(['express']);
var bodyParser = require(['body-parser']);
var cookieParser = require(['cookie-parser']);
var expressSession = require(['express-session']);
var mongoose = require(['mongoose']);
var mongoStore = require(['connect-mongo'])({session: expressSession});
require(['./models/users.js']);
mongoose.connect('mongodb://localhost/userregistration');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views',__dirname + '/views');
app.set('view engine','html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge:60*60*1000 },
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
require('./routes')(app);
app.listen(80);
looking at the logs, the code is giving the error at:
mongoose.connect('mongodb://localhost/userregistration');
I think you forgot to require express-session.
Here is the example
ExpressSession
app.use(express.session({
secret: 'SECRET',
cookie: {maxAge:60*60*1000 },
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
connect-mongo has a special option for using Mongoose connections, try using that:
store: new mongoStore({
mongoose_connection: mongoose.connection,
collection: 'sessions'
})
If that doesn't fix it, please post more information (like a full stack trace and the actual code you're running, since those require's don't look right).
// Replace 'db' by 'mongooseConnection '
app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge: 60 * 60 * 1000},
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions'
})
}));

Resources