You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose配置MongoDB TTL失效:数据提前被删除问题排查

MongoDB TTL索引配置24小时过期但数据2分钟即被删除的解决方案

问题场景

使用Node.js + Mongoose(版本:Node 19.7.0、Mongoose 7.0.1、MongoDB 6.0.4)配置数据24小时后自动删除,代码中设置expireAfterSeconds为86400(246060),但实际数据仅2分钟就被删除。即使调整TTL为5分钟,问题依旧存在。

相关代码:

const expTime = 24 * 60 * 60;

const schema = new Schema({
    a: {
        type: String,
        required: true
    },
    b: {
        type: String
    }
}, { timestamps: true });

schema.index({ createdAt: 1 }, { expireAfterSeconds: expTime });
const model = mongoose.model("example", schema);

//...
model.create({ a, b, "createdAt": new Date() })
    .then(//...)
    .catch((e) => {
        console.error(e);
        //...
    });

数据查询日志显示,数据在创建后约3分钟被删除:

10:34:05 AM {a: '...', b: '...', createdAt: '2023-03-09T09:34:05.314Z', updatedAt: '2023-03-09T09:34:05.425Z'}

10:35:00 AM {a: '...', b: '...', createdAt: '2023-03-09T09:34:05.314Z', updatedAt: '2023-03-09T09:34:05.425Z'}

10:36:00 AM {a: '...', b: '...', createdAt: '2023-03-09T09:34:05.314Z', updatedAt: '2023-03-09T09:34:05.425Z'}

10:37:00 AM undefined

排查过程

执行MongoDB命令检查TTL索引配置:

db.getCollection("example").getIndexes().filter(x => x.expireAfterSeconds)

发现数据库中存在错误的TTL索引配置,与代码设定的86400秒不符。

解决方法

重新初始化数据库(或手动删除错误的TTL索引后重新创建正确索引),确保索引配置与代码逻辑一致。

验证结果

重新初始化后,正确的TTL索引配置如下,数据可按预期24小时后自动删除:

[
  {
    v: 2,
    key: { createdAt: 1 },
    name: 'createdAt_1',
    background: true,
    expireAfterSeconds: 86400
  }
]

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 15:52:46