node.jsmongodbmongooseexpress-sessionconnect-mongo

How to find and edit a session with express-session and connect-mongo?


I use express-session and connect-mongo to deal with user sessions.

I need to figure out how to search the sessions database for a specific user and update it.

I've tried querying the database with a fake schema and am able to find it, but when I try to save it gives an error saying the ID doesn't match, but also when I try to log the ID from the returned document, it's undefined.

ERROR:

Cast to ObjectId failed for value "reWCaAVbumSCW9P6g2qE705Cj6jz0qpD" at path "_id" for model "sessions"

CODE:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const SessionSchema = new Schema({}, { strict: false });
const Session = mongoose.model('sessions', SessionSchema, 'sessions');

module.exports = function (userId, callback) {

    console.log('finding session for',userId);

    Session.findOne({session: {$regex: userId}},(err, session)=>{
        if (err) return callback(err);
        if (!session) return callback('user session not found');

        //parse session
        var sessionJson = JSON.parse(session['_doc'].session);

        //add reset flag
        sessionJson.passport.user.resetSession = true;

        //save back to document
        session['_doc'].session = JSON.stringify(sessionJson);

        //save session to database
        session.save((err, savedSession)=>{
            if (err) return callback(err);

            //success
            return callback(null);
        });
    });
};

Can anyone figure out why the _id field is having problems, or point me towards a better way of editing sessions? Note: this is not editing the session of the logged in user, but for any user.


Solution

  • There were two problems with my above attempt.

    First I had to to specify lean:true in the options for findOne, which finally returned the sessions ID. Because of this I also has to use Session.findOneAndUpdate() instead of document.save().

    Then, for some reason, the IDs for sessions seem to be saved as strings, not as the normal mongoose ID type. So in the schema I specified the ID type to be string.

    new Schema({_id: String}, { strict: false });
    

    After this I was able to make updates to my sessions.