I’m trying to create a simple connection to my MongoDB server from my node application, both hosted locally. However, I keep facing the following error in the STDOUT for the node app before it crashes:
MongoExpiredSessionError: Cannot use a session that has ended
It first looked like I closed a connection and then used it again, but I haven’t closed any connections I opened (testing purposes).
Next, I thought that maybe restarting the node app might work, but it didn’t.
However, if I restart both the node app, and the mongo server, no matter how many times I refresh the route on the browser, I don’t face the error. The error only reoccurs when I kill the node process and relaunch it (without relaunching the mongo server). After that, relaunching node doesn’t make a difference until I relaunch the mongo server too.
Can someone figure out what’s going on?
Hi @Harsh_Narang and welcome in the MongoDB Community !
“Session” sounds more like a transaction session than a connection issue to me but I could be wrong. Are you using transactions and sessions in your code?
I wasn’t sure exactly how sessions in mongoDB worked and the link you shared took me a little bit by surprise.
Then I tried to make an educated guess that the session might refer to an express session. I then changed my code from:
app.use(session({
resave: false,
saveUninitialized:false,
secret: "irandom secretl"
}));
MongoDB.connectDB(function(err) {
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var logoutRouter = require('./routes/logout');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/logout', logoutRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
});
to just moving the app.use(‘session’) inside the connectDB call.