如何在 5 分钟内删除 mongoDB 架构

How can I make a mongoDB schema delete in 5 min

所以我制作了一个验证码之类的东西,他们得到了代码然后他们就可以验证了。但是,我想让它在创建后 5 分钟内过期(因此数据库中没有随机填充的东西)我将如何去做。

您可以添加 expireAt 作为 time-to-live 参数与 createIndex

To create a TTL index, use the createIndex() method on a field whose value is either a date or an array that contains date values, and specify the expireAfterSeconds option with the desired TTL value in seconds.

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )

文档将在 1 小时后过期,并将被 mongodb 自动删除。

勾选这个documentation | TTL indexes

更新:

在 mongoose 中,您可以直接在 Schema 构造函数中使用此参数

const schema = Schema({ name: String, timestamp: Date, metadata: Object }, {
  expireAfterSeconds: 86400
});