-2

我在为 mongodb 使用 typegoose 实现 TTL 时遇到问题。基本上,如果文档超过 30 秒,我想从集合中删除它。

@ObjectType("TokenResetPasswordType")
@InputType("TokenResetPasswordInput")
@index(
   { createdAt: -1, confirmed: 1 },
   { expireAfterSeconds: 30, partialFilterExpression: { confirmed: false } }
)
export class TokenResetPassword {
    @Field()
    @Property({ lowercase: true, required: true, unique: true })
    email: string;

    @Field(() => [User], { nullable: true })
    @Property({ ref: "User", default: "" })
    user?: Ref<User>;

    @prop({ default: Date.now, index: true })
    createdAt?: Date;
}
4

1 回答 1

1

https://docs.mongodb.com/manual/core/index-ttl/

TTL 索引是特殊的单字段索引,MongoDB 可以使用它在一定时间或特定时钟时间后自动从集合中删除文档。

您需要单独为字段创建expireAfterSeconds索引createdAt,而不是同时为两个字段创建索引。

另请注意:

https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation

删除操作的时机

TTL 索引不保证过期数据会在过期后立即被删除。文档过期和 MongoDB 从数据库中删除文档的时间之间可能存在延迟。

删除过期文档的后台任务每 60 秒运行一次。因此,在文档到期和后台任务运行之间的时间段内,文档可能会保留在集合中。

由于删除操作的持续时间取决于您的 mongod 实例的工作负载,因此在后台任务运行之间的 60 秒时间间隔之后,过期数据可能会存在一段时间。

于 2021-04-20T11:28:21.877 回答