如何根据架构中的另一个字段设置 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,然后在预保存函数中根据 expireAt
和 accountType
字段的值设置 deletedAt
。
关于node.js - Mongoose - 如何根据另一个字段更改 TTL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71007594/