Delete from collection after age


#1

Quick question:

I’m looking to delete any messages in my app that are 3 days old (though this can easily be changed to a week or whatever). This is because there will be many chatrooms and I’ve quickly realised implementing a bottom-to-top infinite scroll method is troublesome or ugly and I don’t want users to download an entire collection if it contains records that are months old. No-one (in a chat app at least) will want to retain messages that are more than a few days old anyway!

I downloaded the Synced-cron package and here is the code I have so far:

Meteor.startup(function () {

    SyncedCron.add({
        name: 'Remove messages',
        schedule: function(parser) {
            // parser is a later.parse object
            return parser.text('every day');
        }, 
        job: function() {
            var three_days_ago = new Date(new Date.getTime() - (3600000*72));
            var getMessage = Messages.find({ createdAt: {$lte: three_days_ago} });
            
            
            // This is where I'm stuck!
        }
    });

    // start the cron daemon
    SyncedCron.start();
});

This is running on the server.

You can see where I’m stuck! My mind is just blank and my javascript isn’t the best (but improving, thanks to Meteor!) but I hope one of you kind gentlemen could point me in the right direction here.

Thanks in advance!

Tom.


#2

Hi, simple Messages.remove({ createdAt: {$lte: three_days_ago} }); instead .find should be what you are looking for.

See also: http://docs.meteor.com/#/full/remove


#3

Looks like that should work! It didn’t delete any of my test data when I started it running so looking good :thumbsup: