Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)

like image 563
Brandon A Avatar asked Dec 19 '22 12:12

Brandon A


2 Answers

You could use

Parse.Object.destroyAll(users); // As per your code – what you call users here are actually posts

See: http://parseplatform.org/Parse-SDK-JS/api/classes/Parse.Object.html#methods_destroyAll

Also, consider using Parse.Cloud.afterDelete on Parse.User (if that is what you mean by "deleting account") to do cleanups such as these.

Oh, and just to be complete, you don't need the save() routine after destroyAll()

like image 134
John Doe Avatar answered Jan 13 '23 02:01

John Doe


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);
    });
});
like image 26
jeffdill2 Avatar answered Jan 13 '23 00:01

jeffdill2