有没有一种标准的方法可以在某个时间使用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?

本文关键字:moment Meteor js Mongo 文档 删除 集合 时间 一种 标准 方法      更新时间:2023-09-26

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

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()如何处理线程,所以如果我有数百或数千个这样的调用,我想知道它是否会引起问题。有人能推荐一种更好的方法来实现这一点吗?

提前谢谢。

edit:使用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. 从技术上讲,如果它在多个服务器实例上运行,这不会中断,但理想情况下,它只在一个服务器实例中运行。也许它可以在自己的过程中运行