Removing old data (automatically)


I’m trying to automatically remove old data, data that is 30 minutes old should be deleted from the mongoDB.

My assumption is to write something like this (server-sided)

Meteor.startup(() => {

var currDate = new Date();
var hours = currDate.getHours();
var minutes = currDate.getMinutes();
var total = hours*24 + minutes;
var minuteMargin = 30;
var sum = total - minuteMargin;
Collection.remove( {‘createdAt’: $gt sum});


Hey, first things first, I think you can use getMinutes() and setMinutes() methods. Please have a look at the documentation :slight_smile:

So basically by using these methods you can update the logic like this

const date = new Date()
date.setMinutes(date.getMinutes() - 30)
// So date should point out 30 mins earlier from now

If you desire removing old data every 30 mins, you can create a cron job for that by using percolade:sycned-cron. Go ahead and take a look at the documentation :slight_smile:

You can create a cron job that runs approximately every 30-31 mins to remove old data.

Once you create the cron job, what you should do is calling SyncedCron.start()


Meteor.startup() => {


Or you could just use a setInterval

this.autorun won’t work in this case because there isn’t a reactive dependency in your function, especially not one that is invalidated on a schedule.


Or, do (virtually) nothing and let MongoDB remove the documents for you.

The only thing you need to do is set up an index on the collection with an expireAfterSeconds property on a date field. In Meteor, you set the index in the server’s Meteor.startup() with one of the following methods:

// The "traditional" way
Meteor.startup(() => {
  someCollection._ensureIndex({ someDateField: 1 }, { expireAfterSeconds: 1800 });
// The "modern" way
Meteor.startup(async () => {
  await someCollection.rawCollection().createIndex({ someDateField: 1 }, { expireAfterSeconds: 1800 });