Search code examples
javascriptparse-platformparse-framework

Parse Cloud Code: Delete All Objects After Query


Scenario

I have an app that allows users to create an account, but also allows the user's the ability to delete their account. Upon deletion of their account I have a Cloud Code function that will delete all of the "Post"s the user has made. The cloud code I am using is...

//Delete all User's posts
Parse.Cloud.define("deletePosts", function(request, response) {

    var userID = request.params.userID;

    var query = new Parse.Query(Parse.Post);
    query.equalTo("postedByID", userID);
    query.find().then(function (users) {

        //What do I do HERE to delete the posts?

        users.save().then(function(user) {
        response.success(user);
        }, function(error) {
        response.error(error)
        });

    }, function (error) {

         response.error(error);

    });

});

Question

Once I have the query made for all of the user's posts, how do I then delete them? (see: //What do I do HERE?)


Solution

  • Updates in-line below below your "What do I do HERE..." comment:

    NOTES:

    1. You don't need to call the save() method, so I took that out.

    2. This, of course, is merely a matter of personal preference, but you may want to choose a parameter name that makes a little more sense than "users", since you're really not querying users, but rather Posts (that just happen to be related to a user).


    Parse.Cloud.define("deletePosts", function(request, response) {
        var userID = request.params.userID;
    
        var query = new Parse.Query(Parse.Post);
        query.equalTo("postedByID", userID);
        query.find().then(function (users) {
    
            //What do I do HERE to delete the posts?
            users.forEach(function(user) {
                user.destroy({
                    success: function() {
                        // SUCCESS CODE HERE, IF YOU WANT
                    },
                    error: function() {
                        // ERROR CODE HERE, IF YOU WANT
                    }
                });
            });
        }, function (error) {
             response.error(error);
        });
    });