I am using connect-mongo
with express-session
, and the session data is being written to Mongo as expected.
我正在使用connect-mongo和express-session,会话数据正按预期写入Mongo。
However, I would like to reuse the sessions
collection that connect-mongo
uses to write my own fields in that collection on top.
但是,我想重用connect-mongo用于在该集合中编写我自己的字段的会话集合。
I have defined my own sessions models in sessions.js
such as:
我在sessions.js中定义了自己的会话模型,例如:
const mongoose = require('mongoose');
const SessionSchema = new mongoose.Schema({
_id: {},
session: {},
expires: {},
myNewVariable: {}
});
const Sessions = mongoose.model('sessions', SessionSchema);
module.exports = {Sessions};
Then, in my server file I have:
然后,在我的服务器文件中,我有:
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)); // prints OK!
// Do something with the session
}).catch((e) => console.log('Something went wrong: %s', e));
});
What really surprises me is that the print statement above actually logs the updated session object. However, when I inspect the database later the documents are not updated.
令我惊讶的是,上面的print语句实际上记录了更新的会话对象。但是,当我稍后检查数据库时,文档不会更新。
I have also tried creating a completely different SessionsAlternative
collection. In that case, the collection is updated correctly. That would be a solution, but it wouldn't be optimal as conceptually what I'm trying to write should belong in a single sessions collection.
我也尝试过创建一个完全不同的SessionsAlternative系列。在这种情况下,集合会正确更新。这将是一个解决方案,但它不是最佳的,因为从概念上我正在尝试编写的应该属于单个会话集合。
Is this possible at all, and if so, what am I doing wrong?
这有可能吗?如果是的话,我做错了什么?
1 个解决方案
#1
0
Why not directly save to session?
为什么不直接保存到会话?
req.session.myNewVariable = "abc";
req.session.myNewVariable =“abc”;
#1
0
Why not directly save to session?
为什么不直接保存到会话?
req.session.myNewVariable = "abc";
req.session.myNewVariable =“abc”;