下面是可以通过 mongo 终端设置集合的过期时间(一个 TTL)的命令:
db.log.events.ensureIndex( { "status": 1 }, { expireAfterSeconds: 3600 } )
如何使用 mongoose 从 Node.js 中的代码执行此操作?
最佳答案
在 Mongoose 中,您可以通过 expires
在 Date
字段上创建 TTL 索引。该字段的架构定义中的属性:
// expire docs 3600 seconds after createdAt
new Schema({ createdAt: { type: Date, expires: 3600 }});
注意:
createdAt
设置为当前时间,或者按照建议添加 default
为您执行此操作 here .
{ createdAt: { type: Date, expires: 3600, default: Date.now }}
https://stackoverflow.com/questions/14597241/