Introduction to connect-mongodb-session
connect-mongodb-session
is a MongoDB-backed session store for Express and Connect-based Node.js applications. This module allows developers to store session data in a MongoDB database, facilitating the management of user sessions in a scalable and efficient manner.
In this guide, we will explore various APIs provided by connect-mongodb-session
through practical code snippets and an app example.
Setting Up connect-mongodb-session
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const store = new MongoDBStore({
uri: 'mongodb://localhost:27017/connect_mongodb_session_test',
collection: 'mySessions'
});
store.on('error', function(error) {
console.log(error);
});
app.use(require('express-session')({
secret: 'This is a secret',
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 14 // 14 days
},
store: store,
resave: true,
saveUninitialized: true
}));
Fetching a Session from the Database
store.get('sessionId', function(error, session) {
if (error) {
console.log(error);
} else {
console.log(session);
}
});
Creating and Updating Sessions
store.set('sessionId', { foo: 'bar' }, function(error) {
if (error) {
console.log(error);
}
});
Destroying a Session
store.destroy('sessionId', function(error) {
if (error) {
console.log(error);
}
});
Counting Sessions
store.length(function(error, count) {
if (error) {
console.log(error);
} else {
console.log(count);
}
});
Example App
Here’s a simple Express app demonstrating the usage of connect-mongodb-session
:
const express = require('express');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const app = express();
const store = new MongoDBStore({
uri: 'mongodb://localhost:27017/connect_mongodb_session_test',
collection: 'mySessions'
});
store.on('error', function(error) {
console.log(error);
});
app.use(session({
secret: 'This is a secret',
resave: true,
saveUninitialized: true,
store: store
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.setHeader('Content-Type', 'text/html');
res.write(`views: ${req.session.views}
`);
res.write('expires in: ' + (req.session.cookie.maxAge / 1000) + 's
');
res.end();
} else {
req.session.views = 1;
res.end('welcome to the session demo. refresh!');
}
});
app.listen(3000, () => {
console.log('App is listening on port 3000');
});
If you have any questions or comments, feel free to leave them below!
Hash: 2e2d4a87eb4c1f10523f03cdc9dba75c170dbdd6039f338a55e3a99d469ad99e