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

寵の児 提交于 2019-12-11 11:13:33

问题


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?


回答1:


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);
    });
});


来源:https://stackoverflow.com/questions/33476587/delete-objects-inparse-after-a-set-amount-of-time-from-a-specific-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!