Skip to content

API Cleaner Function

Romain Francois edited this page Dec 19, 2016 · 1 revision

Principle

Information have a maximum TTL (Time To Live) of 7 days. So, with a large number of users we need to clean and delete old information : expired information.
To make this possible the server is running a CRON task every 30 minutes.
Basically we look the if the expiry date precedes current time. If it is true, we delete the information.

Prerequisites

var moment		    = require('moment');
var Info 		    = require('./models/Info');
  • Moment is used to handle datetimes.
  • Info is used to handle Info model and talk with mongoDB.

The function

module.exports = {
	deleteOldInfo() {
		var now = moment().utc().format();

		Info.remove({expirydate: {$lt: now} }, function(err) {
			if(err) {
				console.log('Error when trying to delete old infos');
				return;
			}
			console.log('//////// Database Cleaned ////////');
		});
	}
};

We initialise the variable now with the current datetime.
Note: The date is in UTC format (ISO 8601, ie: 1977-04-22T06:00:00Z)

var now = moment().utc().format();

Then we search and remove all the information which precedes this date.
$lt selects the documents where the value of the field is less than (i.e. <) the specified value. More information here
If the request is done without errors, 'Database cleaned' is displayed in the console.

Info.remove({expirydate: {$lt: now} }, function(err) {
	if(err) {
		console.log('Error when trying to delete old infos');
		return;
	}
	console.log('//////// Database Cleaned ////////');
});

Clone this wiki locally