Mongoose and connect-mongo

Viewed 1855

I am using mongoose for managing relationships between data and I am trying to use connect-mongo to store specific sessions in the database.

It looks like that we need to connect twice to the db, one with mongoose and another one with connect-mongo.

I am using the following code to initialise a connection for mongoose

await mongoose.connect(this._connectionUrl, this._connectionOptions);

Initialising a new store every time (not sure if I am correct regarding code initialisation).

app.use(session({
            // secret: config.sessionSecretKey,
            secret: "secretkey",
            resave: true,
            saveUninitialized: true,
            cookie: { maxAge: 19 * 60000 }, // store for 19 minutes
            store: MongoStore.create({
                mongoUrl: this._connectionUrl,
                mongoOptions: this._connectionOptions // See below for details
            })
        }))

Is there any way that I can pass the connection from mongoose to mongo-connect Store?

2 Answers

i'm lookin for a solution too and just read this on the "migration guide" of connect-mongo

For the options, you should make the following changes:

Change url to mongoUrl Change collection to collectionName if you are using it Keep clientPromise if you are using it mongooseConnection has been removed. Please update your application code to use either mongoUrl, client or clientPromise To reuse an existing mongoose connection retreive the mongoDb driver from you mongoose connection using Connection.prototype.getClient() and pass it to the store in the client-option. Remove fallbackMemory option and if you are using it,

and there's this example https://github.com/jdesboeufs/connect-mongo/blob/master/example/mongoose.js

I've just been digging through the docs and through a few other SO responses. I've found this works really well with the new version of connect-mongo.

const session = require('express-session');
const MongoStore = require('connect-mongo');

app.use(
    session({
        secret: "secretkey",
        resave: true,
        saveUninitialized: true,
        cookie: { maxAge: 19 * 60000 }, // store for 19 minutes
        store: MongoStore.create({
            client: mongoose.connection.getClient()
        })
    })
);

It is recommended by the devs for connect-mongo to utilise the connection object for mongoose to retrieve the client to ride the same connection so you don't have to setup two separate connections. This seems like a really clean way to do it but comment if you spot anything off!

This was pulled from the bottom of the connect-mongo migration guide here

Related