是否有一种标准方法可以在特定时间使用 Meteor 和 moment.js 从集合中删除 Mongo 文档?

Is there a standard way to remove a Mongo document from a collection at a certain time using Meteor and moment.js?

我正在尝试找到一种更好的方法来确保某些文档在特定时间从 mongo 集合中删除,这对每个文档都是唯一的。删除项目时,我还需要 运行 一些方法。我查看了 TTL 索引,但似乎它们不允许任何类型的回调,从我读到的过程中,每分钟仅 运行s 一次删除文档,这不够具体我需要的。以下是我想出的:

var check_frequency = 30000;
Meteor.setInterval((function() {
    // figure out what elements will expire within the next check period
    var next_check = moment().add(check_frequency, 'milliseconds');
    var next_string = next_check._d.toISOString();

    var ending_items = items.find({'time_to_end': {$lt : next_string}});

    ending_items.forEach(function(db_object) {
        var time_from_now = moment(db_object.time_to_end) - moment();
        Meteor.setTimeout(function() {
            removeAndReport(db_object._id);
        }, time_from_now);

    });
}), check_frequency);

我担心的是我不确定 Meteor.setTimeout() 如何处理线程,所以如果我有成百上千个这样的调用,我想知道它是否会导致问题.谁能推荐一个更好的方法来完成这个?

提前致谢。

编辑:运行 Meteor 或 cron 的后台作业不是我唯一关心的问题。我意识到我可以用 cron 作业完成同样的事情,但我宁愿不每秒查询一次我的数据库只找到 3 个过期项目,而不是每 30 秒查询一次数据库,并找出哪些元素将在下一个时间段。

似乎更简单的解决方案是在每个文档中存储删除日期,而不是 TTL。假设您有一个名为 Messages 的集合,并且每个文档都有一个 removeAt 字段。然后您可以执行以下操作:

var timeout = 500;
Meteor.setInterval((function() {
  // remove any messages that should have been removed in the past
  Messages.remove({removeAt: {$lte: new Date}});
}), timeout);

备注:

  1. 确保索引 removeAt,这样 remove 就不需要扫描您的整个集合。
  2. 从技术上讲,如果它 运行 出现在多个服务器实例上,这不会破坏,但理想情况下它只会 运行 出现在一个服务器实例上。也许它可以是 运行 在它自己的进程中。