node.js - Mongoose - 如何根据另一个字段更改 TTL?

标签 node.js mongodb mongoose schema ttl

如何根据架构中的另一个字段设置 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)

我已经尝试过了 创建时间:{ 类型:日期,过期时间:600 }, KeySchema.index({createdAt: 1}, {expireAfterSeconds: 3600}) expireAt: { type: Date, default: Date.now, index: { expires: '5s' }}

最佳答案

MongoDB 使用 index 处理 TTL

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

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

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

关于node.js - Mongoose - 如何根据另一个字段更改 TTL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71007594/

相关文章:

javascript - 如何向cloud9中的server.js发送post请求

node.js - 在 mongoDB 上搜索子字段

node.js express集群和高CPU使用率

node.js - 如何使用 mongoose 一次返回 25 个结果

node.js - 使用 mocha 运行时,仍然收到 babel-plugin-syntax-dynamic-import 动态导入的语法错误

node.js - 如何在 Sequelize upsert 中获取插入或更新记录的 ID?

node.js - 如何在无需全局安装 ts-node 或 npx 的情况下完全运行 nodemon + ts-node + typescript?

javascript - chai eql 将相等数组报告为不同

mongodb - Docker运行不正常

Node.js + Mongoose/Mongo 和缩短的 _id 字段