connect-mongodb-session
MongoDB-backed session storage for connect and Express. Meant to be a well-maintained and fully-featured replacement for modules like connect-mongo
MongoDBStore
This module exports a single function which takes an instance of connect
(or Express) and returns a MongoDBStore
class that can be used to
store sessions in MongoDB.
It can store sessions for Express 4
If you pass in an instance of the
express-session
module
the MongoDBStore class will enable you to store your Express sessions
in MongoDB.
The MongoDBStore class has 3 required options:
uri
: a MongoDB connection stringdatabaseName
: the MongoDB database to store sessions incollection
: the MongoDB collection to store sessions in
Note: You can pass a callback to the MongoDBStore
constructor,
but this is entirely optional. The Express 3.x example demonstrates
that you can use the MongoDBStore class in a synchronous-like style: the
module will manage the internal connection state for you.
var express = ;var session = ;var MongoDBStore = session; var app = ;var store = uri: 'mongodb://localhost:27017/connect_mongodb_session_test' collection: 'mySessions'; // Catch errorsstore; app; app; server = app;
It throws an error when it can't connect to MongoDB
You should pass a callback to the MongoDBStore
constructor to catch
errors. If you don't pass a callback to the MongoDBStore
constructor,
MongoDBStore
will throw
if it can't connect.
var express = ;var session = ;var MongoDBStore = session; var app = ;var numExpectedSources = 2;var store = uri: 'mongodb://bad.host:27000/connect_mongodb_session_test?connectTimeoutMS=10' databaseName: 'connect_mongodb_session_test' collection: 'mySessions' { // Should have gotten an error }; store; app; app; server = app;
It supports several other options
There are several other options you can pass to new MongoDBStore()
:
var express = ;var session = ;var MongoDBStore = session; var store = uri: 'mongodb://localhost:27017/connect_mongodb_session_test' collection: 'mySessions' // By default, sessions expire after 2 weeks. The `expires` option lets // you overwrite that by setting the expiration in milliseconds expires: 1000 * 60 * 60 * 24 * 30 // 30 days in milliseconds // Lets you set options passed to `MongoClient.connect()`. Useful for // configuring connectivity or working around deprecation warnings. connectionOptions: useNewUrlParser: true useUnifiedTopology: true serverSelectionTimeoutMS: 10000 ;