【问题标题】:Mongoose - How to change the TTL based on another field?Mongoose - 如何根据另一个字段更改 TTL?
【发布时间】:2022-02-07 02:05:22
【问题描述】:

如何根据架构中的另一个字段设置 TTL?我想将 expireAt 字段设置为 accountType 的任何值(该值可以是一个月/一周/一天)。但是,此代码不会使文档过期或更改过期日期。我尝试了 TTL 字段的多种变体,但似乎都不起作用。

import mongoose from 'mongoose'
import { generateKey } from '../lib/generateKey'

const KeySchema = new mongoose.Schema({
  key: {
    type: String,
    default: generateKey,
    required: true,
  },
  accountType: { /* The value can be a month, a week or a day*/
    type: String,
    required: true,
  },
  dailyLimit: {
    type: Number,
    default: 0,
    required: true,
  },
  expireAt: {
    type: Date,
    default: Date.now,
    index: {
      expireAfterSeconds: 60
    }
  },
})

KeySchema.pre('save', function (next) {
  switch (this.accountType) {
    case 'month':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 30
      }
      break
    case 'week':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 7
      }
      break
    case 'day':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 1
      }
      break
  }

  next()
})

export default mongoose.models.Key || mongoose.model('Key', KeySchema)

我试过了 createdAt: { type: Date, expires: 600 }, KeySchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 }) expireAt: { type: Date, default: Date.now, index: { expires: '5s' }}

【问题讨论】:

    标签: node.js mongodb mongoose schema ttl


    【解决方案1】:

    MongoDB 使用 index 处理 TTL

    Mongoose 根据架构在创建所有其他索引的同时创建 TTL 索引,并且所有文档都使用相同的索引。

    虽然可以基于字段值创建部分索引,但 MongoDB 不允许创建包含相同键但不同选项(如过期)的多个索引。

    您可以将另一个字段添加到名为 deleteAt 的方案中,并将 expireAfterSeconds 设置为 0,然后在基于预保存函数集 deletedAt 的情况下,而不是尝试更改每个文档的索引选项 expireAfterSeconds expireAtaccountType 字段的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      相关资源
      最近更新 更多