0

is there any possible method for me to delete specific session from mongoDB?

My scenario is to allow 'myself' to delete specific session from DB (other user session). Reading from connect-mongo docs, I can use destory but looks like this method is to destroy my own session (req.session.destroy()). Is there a way for me to achived this?

something like

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


MongoStore.destroy('some random user session id')

My config: Express + express-session with connect-mongo + mongoDB

rushgsp
  • 11
  • 1
  • 4

1 Answers1

0

I am trying to do something similar. During testing, I want to be able to clear all session. I sort of have this working.

My approach is just to reach into the sessions collections and delete all documents.

async clearSessions (req,res,next) {
    const uri = getDbConnectionString()
    const client = new MongoClient(uri,{ useNewUrlParser: true, useUnifiedTopology: true });
    try {
        await req.session.destroy();
        await client.connect();
        const sessions_result=  await client.db(`${process.env.DBNAMEDEV}`).collection("sessions").deleteMany({});
       // console.log(sessions_result)
       await client.close();
       res.send("cleared")

       return
    } catch (e) {
        console.error(e);

    }
    res.send("failed")
}

This code is called via the route /api/setup/clearsessions. *PREVIOUSLY this was the case: The code works, but then connect-mongo throws and error saying "Error: unable to find the session to touch". However, the error thrown by connect-mongo does not cause problems

I fixed the errors by adding await req.session.destroy();.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
SwimLeft
  • 9
  • 2