I am utilizing connect-mongo
in conjunction with express-session
, and the session data is successfully being stored in Mongo.
However, I want to enhance the sessions
collection utilized by connect-mongo
in order to include my own fields on top of it.
I have created my custom sessions models in a file named sessions.js
as shown below:
const mongoose = require('mongoose');
const SessionSchema = new mongoose.Schema({
_id: {},
session: {},
expires: {},
myNewVariable: {}
});
const Sessions = mongoose.model('sessions', SessionSchema);
module.exports = {Sessions};
In my server file, I have included the following:
const session = require('express-session');
const {mongoose} = require('./db/mongoose.js');
const {Sessions} = require('./models/sessions.js');
const MongoStore = require('connect-mongo')(session);
app.use(session({
secret: SECRET,
resave: true,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.post('/myRoute', function(req, res, next) {
Sessions.findOneAndUpdate(
{_id: req.session.id},
{$set:{myNewVariable: myNewValue}},
{new: true}).then((session) => {
console.log('session: ' + JSON.stringify(session)); // displays correctly!
// Perform operations with the session
}).catch((e) => console.log('Something went wrong: %s', e));
});
The surprising part is that the print statement above shows the updated session object. However, upon inspecting the database later, the documents remain unchanged.
Attempting to create a completely different SessionsAlternative
collection yielded successful updates. While this could be a workaround, it does not align with the intended concept of consolidating all data into a single sessions collection.
Is there a way to achieve this, and if so, what steps am I missing?