mongo 设置TTL index自动过期

mongo存储的一些数据,例如日志,很重要,不能没有,但产生的速度太快太多,一段时间后就会产生大量日志,最好能过一段时间后自动删除。

这就可以尝试使用TTL index。在mongoose 中可以这样设置

const mongoose = require('mongoose');

const logSchema = new mongoose.Schema({
  message: String,
  createdAt: {
    type: Date,
    default: Date.now,
    index: { expires: '30d' }
  }
});

const Log = mongoose.model('Log', logSchema);

但我之前写过一个通用的添加createdAt 字段的函数。担心设置的index 会被覆盖。

const schema = new Schema(_schema, {
    timestamps: {
      createdAt: 'createdAt',
      updatedAt: 'updatedAt',
    },
    toObject: { virtuals: true },
    toJSON: { virtuals: true },
  });

timestamps 选项是 Mongoose 提供的一个便捷功能,它会自动为模型添加 createdAtupdatedAt 字段,并且为这些字段设置默认值和索引。如果你在 _schema 中也定义了 createdAt 字段,那么 timestamps 选项中的设置将会覆盖你在 _schema 中的设置。

在这种情况下,createdAt 字段的 expires 设置将不会生效,因为 timestamps 选项会重新定义 createdAt 字段,并且不会包含 expires 设置。

如果你需要同时使用 timestamps 功能和设置 createdAt 字段的过期时间,你可以这样操作:

  1. 不在 _schema 对象中显式定义 createdAt 字段。
  2. 使用 timestamps 选项来自动添加 createdAt 字段。
  3. 然后,手动为 createdAt 字段添加 TTL 索引。

示例代码如下:

const schema = new Schema({
  // 其他字段...
}, {
  timestamps: {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
  },
  toObject: { virtuals: true },
  toJSON: { virtuals: true },
});

// 为createdAt字段添加TTL索引
schema.index({ createdAt: 1 }, { expireAfterSeconds: 60 * 60 * 24 * 7 });

注意,在调试的时候,index 被设置之后,再修改时间是不生效的,需要删除 index 后重新执行。

https://www.mongodb.com/docs/manual/tutorial/expire-data/

Leave a Comment

邮箱地址不会被公开。 必填项已用*标注