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

查看:1253
本文介绍了使用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 } )

我如何使用猫鼬在Node.js中的代码中做到这一点?

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

推荐答案

在Mongoose中,您可以通过Date字段上创建TTL索引.该字段的架构定义中的html#schema_Schema-index"rel =" noreferrer> 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设置为当前时间,还是根据建议
  • 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天全站免登陆