【问题标题】:mongodb: expires not workingmongodb:过期不工作
【发布时间】:2018-11-13 09:41:44
【问题描述】:

在 mongoose 5.0.6 中,我希望此架构在创建后 1 分钟使文档过期:

const InvitationTokenSchema = new Schema(
  {
    token: { type: String, required: true },
    createdAt: { type: Date, default: Date.now, expires: '1m' },
    userId: { type: Schema.Types.ObjectId, ref: 'User' },
  },
  {
    usePushEach: true,
  },
);

但是它根本不起作用 - 所有文档都只保留在 mongo 中,而不是被删除。

在 mongo shell 中,getIndexes() 显示如下:

[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "mydb.invitationtokens"
    },
    {
        "v" : 2,
        "key" : {
            "createdAt" : 1
        },
        "name" : "createdAt_1",
        "ns" : "mydb.invitationtokens",
        "expireAfterSeconds" : 60,
        "background" : true
    }
]

可能是什么原因?

【问题讨论】:

  • 这是一个数值而不是字符串。此外,TTL 调度程序最多每分钟执行一次。如果您想要更多粒度,请编写您自己的调度程序。
  • @NeilLunn 1 分钟对我来说没问题,但它永远不会执行。
  • TTL Indexes 架构中expires 的值在expiresAfterSeconds 中使用,它不接受字符串。现实一点,走 5 分钟。这是300 秒而不是'5m'
  • @NeilLunn 已更改 expires 到 100,等了 5 分钟,文件还在。现在在索引中显示"expireAfterSeconds" : 100。仅将这个小数字用于调试目的。
  • @NeilLunn Mongoose 使用ms1m 等字符串转换为60 秒。语法绝对没问题,getIndexes 输出证明了这一点。斯坦利,你能添加一个你希望被删除的文件的例子吗?我无法重现它。

标签: node.js mongodb mongoose


【解决方案1】:

当我看到你的代码时,它是正确的。 此外,该值应为 String,您也可以使用 '1m'。 您需要将 mongoose 更新到最新版本。

使用:npm update mongoose

更多详情请在此处搜索“过期”:http://mongoosejs.com/docs/api.html

【讨论】:

  • 谢谢!升级到mongoose 5.1.4 后问题已解决。
猜你喜欢
  • 2015-11-18
  • 2014-09-17
  • 2015-04-24
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
相关资源
最近更新 更多