能不能自动清理呢?大致的代码如下:
var mongoStore = require("connect-mongo")(express);
...
app.use(express.session({
secret : "foo",
store : new mongoStore({
db : "bar"
})
}));
平时在用的时候直接就是:
exports.blah = function(req, resp) {
req.session.user = blahblah;
};
随着时间的推移,发现我的mongodb的相应collection中的session数据越来越多,貌似是因为没有清除引起的?
所以想问一下,怎么让数据库中的session数据自己回收呢?THX。
根据 connect-mongo 的文档:
By connect/express's default, session cookies are set to expire when the user closes their browser (maxAge: null). In accordance with standard industry practices, connect-mongo will set these sessions to expire two weeks from their last 'set'. You can override this behavior by manually setting the maxAge for your cookies -- just keep in mind that any value less than 60 seconds is pointless, as mongod will only delete expired documents in a TTL collection every minute.
即是说,默认情况下 Express 的 session cookie 关闭浏览器后就失效,而 mongo 则会在两周后删除相关记录。
如果想 session 和数据库中的记录同时失效呢,可以这么做:
app.use(express.session({
secret: ......,
cookie: { maxAge: 1 * 60 * 60 * 1000 }, // 1 hour
store: ......
}))