connect-mongo删除过期的session

在使用express-session的时候,使用mongodb存储session,过期的session可以自动被删除,不需要代码中处理。

通过查看源代码发现,在connect-mongo中使用设置索引的方式来自动删除过期的session。

// 初始化connect-mongo的时候 autoRemove的的默认值native
this.autoRemove = options.autoRemove || 'native'
this.writeOperationOptions = options.writeOperationOptions || {}
....

setAutoRemoveAsync() {
	....
  switch (this.autoRemove) {
    case 'native':
      return this.collection.createIndex(
        { expires: 1 },
        Object.assign({ expireAfterSeconds: 0 }, this.writeOperationOptions)
      )
      ....
   }
   ....
 }

在创建索引的时候增加参数 expireAfterSeconds,就可以做到自动删除过期文档;

expireAfterSeconds的使用方法有两种:

  • 设定一条数据多久之后过期

这种用法不需要计算什么时间过期,比较合适的使用场景是记录日志

// 先创建一个索引,设置createdAt对应的时间一个小时之后过期
db.logs.createIndex( { "a": 1 }, { expireAfterSeconds: 3600 } )
// 插入一条数据  设置createdAt为插入数据的当前时间
db.logs.insert( {
   "a": new Date(),
} )
  • 设定一条数据什么时间过期

connect-mongo中使用的就是这种方法

// 比较明显的是expireAfterSeconds为0,那么插入数据的时候就需要指明具体过期日期
db.logs.createIndex( { "a": 1 }, { expireAfterSeconds: 0 } )
db.logs.insert( {
   "a": new Date('September 1, 2020 14:00:00'),
} )
原文地址:https://www.cnblogs.com/walkermag/p/13589319.html