Search code examples
parse-platformparse-cloud-code

delete objects inParse after a set amount of time from a specific class


Hello I have an app that would upload photo's to the sever. Parse only gives us 20gb for storage and so I don't want to go over that limit. I want the server so that it would delete the files if it is 3 days old. So this is the code

Parse.Cloud.job('deleteOldPosts', function(request, status) {
// All access
Parse.Cloud.useMasterKey();

var today = new Date();
var days = 10;
var time = (days * 24 * 3600 * 1000);
var expirationDate = new Date(today.getTime() - (time));

var query = new Parse.Query('post');
    query.lessThan('createdAt', expirationDate);

    query.find().then(function (posts) {
        Parse.Object.destroyAll(posts, {
            success: function() {
                status.success('All posts are removed.');
            },
            error: function(error) {
                status.error('Error, posts are not removed.');
            }
        });
    }, function (error) {});

});

However If I use this code it would delete files from all classes. I just want this code to work on only one class. Is it possible to do so?


Solution

  • When deleting objects in cloud code, use query.each instead of query.find to ensure that you delete all objects matching the query .

    find has the query limitation of 100 objects returned by default (or up to 1000 if limit is used). Source

    Below is your updated code using a promise chain which calls destroy on each Post object. When all of the destroy promises have completed, the success status will be reached, and if any of the destroys fail then the error status will be reached.

    Parse.Cloud.job('deleteOldPosts', function(request, status) {
        // All access
        Parse.Cloud.useMasterKey();
    
        var today = new Date();
        var days = 10;
        var time = (days * 24 * 3600 * 1000);
        var expirationDate = new Date(today.getTime() - (time));
    
        var query = new Parse.Query('post');
        query.lessThan('createdAt', expirationDate);
        query.each(function(post) {
            return post.destroy();
        }).then(function() {
            console.log("Delete job completed.");
            status.success("Delete job completed.");
        }, function(error) {
            alert("Error: " + error.code + " " + error.message);
            status.error("Error: " + error.code + " " + error.message);
        });
    });