Search code examples
iosswiftparse-platform

How can i count the number of followers using parse saved data as shown:


i have saved my followers list as shown in the table image enter image description here

in the "user" column , i've saved the objectId of user being followed and in the "follower" column i've saved the currentUser (follower) now i want to get the number of followers of each user.. how can i do that?


Solution

  • Parse Query for counting objects https://parse.com/docs/ios/guide#queries-counting-objects Where you can execute 1 query to get followers count of 1 user. Which can easily max out parse api limit i.e. (counting object query 160 requests per minute). For this Parse and Me, both not recommend you to use counting Objects especially if you expect significant number of users.

    Parse Recommendation to avoid Count Operations https://parse.com/docs/ios/guide#performance-avoid-count-operations

    You should use parse cloud code(https://parse.com/docs/ios/guide#cloud-code) and have a key in your User table which can keep record of current followers count for that user.

    Cloud code in your case.

    Parse.Cloud.afterSave("Followers", function(request) {
        if(request.object.existed() == true)
            // No need to increment count for update due to some reason
            return;
        });
        // Get the user id for User
        var userID = request.object.get("user");// Or request.object.get("user").id;
        // Query the user in actual User Table
        var UserQuery = Parse.Object.extend("User");
        var query = new Parse.Query(UserQuery);
        query.get(userID).then(function(user) {
        // Increment the followersCount field on the User object
            user.increment("followersCount");
            user.save();
        }, function(error) {
            throw "Got an error " + error.code + " : " + error.message;
        });
    });
    

    Unfollowing might also happen, Leaving After Delete practise to you https://parse.com/docs/ios/guide#cloud-code-afterdelete-triggers