使用 mongoose 在 mongodb 中设置集合的到期时间 [英] Setting expiry time for a collection in mongodb using mongoose

查看:44
本文介绍了使用 mongoose 在 mongodb 中设置集合的到期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是可以通过 mongo 终端使用的命令来设置集合的到期时间(TTL):

Below is the command that can be used via the mongo terminal to set an expiry time for collections (a TTL):

db.log.events.ensureIndex( { "status": 1 }, { expireAfterSeconds: 3600 } )

如何使用 mongoose 从我的 Node.js 代码中执行此操作?

How do I do this from my code in Node.js using mongoose?

推荐答案

在 Mongoose 中,您可以通过 expires 该字段的架构定义中的属性:

In Mongoose, you create a TTL index on a Date field via the expires property in the schema definition of that field:

// expire docs 3600 seconds after createdAt
new Schema({ createdAt: { type: Date, expires: 3600 }});

注意:

  • MongoDB 的数据过期任务每分钟运行一次,因此过期的文档可能会在过期后持续一分钟.
  • 此功能需要 MongoDB 2.2 或更高版本.
  • 您可以在创建文档时将 createdAt 设置为当前时间,或者根据建议添加 default 来为您执行此操作 这里.
    • { createdAt: { type: Date, expires: 3600, default: Date.now }}
    • MongoDB's data expiration task runs once a minute, so an expired doc might persist up to a minute past its expiration.
    • This feature requires MongoDB 2.2 or later.
    • It's up to you to set createdAt to the current time when creating docs, or add a default to do it for you as suggested here.
      • { createdAt: { type: Date, expires: 3600, default: Date.now }}

      这篇关于使用 mongoose 在 mongodb 中设置集合的到期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆