node.js 使用 mongoose 在 mongodb 中设置集合的到期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14597241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:03:33  来源:igfitidea点击:

Setting expiry time for a collection in mongodb using mongoose

node.jsmongodbmongoose

提问by Amanda G

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

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

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

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

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

回答by JohnnyHK

In Mongoose, you create a TTL index on a Datefield via the expiresproperty in the schema definition of that field:

在 Mongoose 中,您可以Date通过该字段expires的架构定义中的属性在该字段上创建 TTL 索引:

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

Note that:

注意:

  • 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 createdAtto the current time when creating docs, or add a defaultto do it for you as suggested here.
    • { createdAt: { type: Date, expires: 3600, default: Date.now }}
  • MongoDB 的数据过期任务每分钟运行一次,因此过期的文档可能会在过期后持续一分钟。
  • 此功能需要 MongoDB 2.2 或更高版本。
  • 您可以createdAt在创建文档时设置为当前时间,或者default按照此处的建议为您添加一个。
    • { createdAt: { type: Date, expires: 3600, default: Date.now }}

回答by Sadegh Teimori

this code is working for me.

这段代码对我有用。

may it help

可能有帮助

let currentSchema = mongoose.Schema({
    id: String,
    name: String,
    packageId: Number,
    age: Number
}, {timestamps: true});

currentSchema.index({createdAt: 1},{expireAfterSeconds: 3600});

回答by Akrion

Providing a string to expiresalso works nicely with Mongoose if you do not want to deal with the expire time calculation and improve the overall readability of the schema.

expires如果您不想处理过期时间计算并提高架构的整体可读性,则提供一个字符串也可以很好地与 Mongoose 配合使用。

For example here we are setting the expiresto 2m(2 minutes) and mongoose would convert to 120 secondsfor us:

例如,这里我们将 设置expires2m(2 分钟),猫鼬将为我们转换为120 秒

var TestSchema = new mongoose.Schema({
  name: String,
  createdAt: { type: Date, expires: '2m', default: Date.now }
});

Mongoose would create an index in the background and auto set the expireAfterSecondsto in this case 120seconds (specified by the 2m).

Mongoose 会在后台创建一个索引,并expireAfterSeconds在这种情况下自动设置为120秒(2m指定)。

It is important to note that the TTL process runs once every 60 secondsso it is not perfectly on time always.

重要的是要注意 TTL 进程每 60 秒运行一次,因此它并不总是完全准时。

回答by Jason Mullings

If you are working with Mongodb Atlas Replica Sets - try:

如果您正在使用 Mongodb Atlas 副本集 - 尝试:

import * as mongoose from 'mongoose'; 

let currentSchema = new mongoose.Schema({
        createdAt: { type: Date, expires: 10000, default: Date.now },
        id: String,
        name: String,
        packageId: Number,
        age: Number
        });

currentSchema.index({"lastModifiedDate": 1 },{ expireAfterSeconds: 10000 });

回答by arr

There is a npm library - 'mongoose-ttl'.:

有一个 npm 库 - 'mongoose-ttl'。:

var schema = new Schema({..});
schema.plugin(ttl, { ttl: 5000 });

you can see all the options of this library: https://www.npmjs.com/package/mongoose-ttl

你可以看到这个库的所有选项:https: //www.npmjs.com/package/mongoose-ttl