MongoDB 文档过早过期 (mongoose) [英] MongoDB documents expiring too soon (mongoose)

查看:78
本文介绍了MongoDB 文档过早过期 (mongoose)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将到期时间设置为 24 小时,但文档在大约 5-10 分钟后到期(我没有准确计时).我究竟做错了什么?我的架构:

I set expiry time to 24 hours, but the documents expire after around 5-10 minutes (I haven't timed it exactly). What am I doing wrong? My schema:

const collectionSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  name: {
    type: String,
    maxLength: 30,
    required: true
  },
  entries: [{ type: mongoose.Schema.Types.ObjectId, ref: "Entry" }],
  expireAt: { type: Date, expires: 60 * 60 * 24 }
});

在 post 路由中,我有条件地设置日期,以便登录的客户端获得数据持久性.

In the post route, I conditionally set the date so that inlogged clients get data persistence.

router.post("/", auth, async (req, res) => {
  let date = null;
  if (!req.user) {
    date = new Date();
  }
  try {
    const collection = {
      userId: req.body.userId,
      name: req.body.name,
      expireAt: date
    };
    const newCollection = await Collection.create(collection);
    res.send(newCollection);
  } catch (error) {
    res.send(error.message);
  }
});

我以为我有时区问题,但是当我检查 MongoDB 指南针中的时间戳时,它与我的时区相匹配.我做错了什么?

I thought I had a time-zone problem, but when I check the time stamp in MongoDB compass, it matches my time-zone. What am I doing wrong?

推荐答案

我对此进行了测试:

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

文档在第二分钟后被删除,我还确认 TTL 索引已正确创建(默认情况下作为背景索引),TTL 为 120 秒.

Documents ware deleted after the second minute and I also confirmed that the TTL index was properly created (as a background one by default) with TTL of 120 seconds.

试试那个时间格式,看看它是否适合你.

Try that time format and see if that works for you.

另请注意,通过您的 mongo 架构对索引进行的任何预期更改都不会反映到您手动删除以前的索引并启动您的应用程序自动创建新的.

Also note that any expected changes to the index via your mongo schema would not be reflected until you manually remove the previous index and start your app to auto-create the new one.

MongoDB 版本:3.6.5

MongoDB version: 3.6.5

这篇关于MongoDB 文档过早过期 (mongoose)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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