Querying the collection directly will only solve part of your problem.
From the looks of it, you're using express-session
and connect-mongo
to manage sessions. This will store the session data (req.session
) as a JSON string in the database:
{
"_id": "fLBj_McMFM-7PwVNsv9ov88vOAgoNiDa",
"session": "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"userId\":\"my-user-id\"}",
"expires": ISODate("2016-07-09T08:47:38.156Z")
}
As you can see, session
is a string, not an object, so you can't query it directly using session.userId
.
If you can't use req.session.destroy()
, you need to perform a regular expression query to match against the user id in the JSON string:
let collection = mongoose.connection.db.collection('sessions');
let query = new RegExp(`"userId":"${userId}"`);
collection.remove({ session : query }, function(e, found) {
console.log(found);
res.json({success: true});
});
It's probably best if userId
is first run through something like escape-string-regexp
to make sure that any special characters are escaped properly.
Note that this isn't a fast query, especially if you have a lot of sessions in your database.
EDIT: I just found the stringify
option for connect-mongo
which, if set to false
, should write the session data as a regular object to MongoDB, and not as a JSON string.