Connect-mongo sessions not being deleted automatically

℡╲_俬逩灬. 提交于 2019-12-02 19:38:58

You haven't set a clear_interval for your sessions .. the connect-mongo default is -1 (or "never"):

clear_interval Interval in seconds to clear expired sessions (optional, default: -1). Values <= 0 disable expired session clearing.

Example of removing expired sessions every hour (3600s):

var sessionStore = new MongoStore({
     db: 'myappsession',
     clear_interval: 3600
});

You should also make sure you have set a maxAge on your sessions to they actually expire (eg using 1 day):

app.use(express.session({
    secret: "myappsecret",
    cookie: { maxAge: 24 * 60 * 60 * 1000 },
    store:sessionStore
}));

I don't know from where the clear_interval options was taken but I'm looking at the code of the latest version:

class MongoStore extends Store {
 constructor(options) {
  options = options || {}

  /* Fallback */
  if (options.fallbackMemory && MemoryStore) {
    return new MemoryStore()
  }

  super(options)

  /* Options */
  this.ttl = options.ttl || 1209600 // 14 days
  this.collectionName = options.collection || 'sessions'
  this.autoRemove = options.autoRemove || 'native'
  this.autoRemoveInterval = options.autoRemoveInterval || 10
  this.transformFunctions = computeTransformFunctions(options, true)

  // ...

setAutoRemoveAsync() {
  const removeQuery = {expires: {$lt: new Date()}}
  switch (this.autoRemove) {
    case 'native':
      return this.collection.createIndex({expires: 1}, {expireAfterSeconds: 0})
    case 'interval':
      this.timer = setInterval(() => this.collection.remove(removeQuery, {w: 0}), this.autoRemoveInterval * 1000 * 60)
      this.timer.unref()
      return Promise.resolve()
    default:
      return Promise.resolve()
  }
}

So the correct way to set auto remove based on that code seems to be:

const store = new MongoStore({
  url: "put db connection string here ...",
  autoRemove: 'interval',     
  autoRemoveInterval: 60 * 24 // In minutes. Default
})

I dont see any trace of a clear_interval option, so it seems to me the suggested solution would have no effect ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!