Using a post-save server hook to update the user profile when creating an entity [Unity]

Sometimes you will store information in a user profile that will depend on other structures. To update the user profile when an entity in another collection is created or updated you can use Server Hooks. They will help you keep this kind of dependency automatically.

In this example, we have a user with this profile structure:

{
    "nickname": "Knight4",
    "country": "Germany",
    "matches_created": 0
}
Let's say we want to increase the number of created_matches in the profile of the user everytime this user creates a match. We can create a post-save server hook related to the matches collection that triggers everytime a new match is created and increases the number of matches created by one. The server hook would look like this:

var newProf = {};

newProf.created_matches = request.user.profile.created_matches +1;

gamedonia.user.update(newProf, false, {
    success: function(results) {
            response.success();
    },
    error: function(error) {
            response.error(error.message);
    }
    } 
);

We use the update call on the user with the overwrite paremeter set to false because we don't want to overwrite the whole profile structure, just the created_matches entry. Now we turn to the client code, for instance, in Unity. We can create a match in the matches collection like this:

Dictionary<string,object> match = new Dictionary<string,object>(); 
match["host"] = GamedoniaUsers.me.profile["nickname"];
GamedoniaData.Create("matches", match, delegate (bool success, IDictionary data) { 
    if (success) {
        //TODO Your success processing
    } else {
        //TODO Your fail processing
    }
});
Remember that before creating an entity in a collection (like a match in the collection called matches) you need to create a collection called matches first in the Dashboard Collections section.
When the match is created, the profile structure of the user will be automatically updated to this one:
{
    "nickname": "Knight4",
    "country": "Germany",
    "matches_created": 1
}

More info here: Server code guide