Rank 3: Container
Okay, so I'm tackling a big problem that I'm facing. I have a NextJS app for movies with various features, such as the ability to write reviews, follow profiles, like playlists, etc. Let's take the example of playlists. I have a playlist collection where each document contains an $id (the unique ID of the playlist), the name of the playlist, and the user who created it. In addition, I have another collection called playlist_liked, where each document represents a like from a user for a playlist and contains the ID of the liked playlist and the ID of the user who liked it.
Now, in my NextJS app, I would like to be able to search for playlists based on their names, BUT I also want to be able to sort them based on the number of likes. The first possibility was to perform a simple search with Appwrite based on the name and then make a request for the number of likes for each playlist, and finally display them based on the number of likes. However, this approach seems very query-intensive in terms of API requests. Because if there are for example millions of likes it becomes impossible right? So, wouldn't it be wiser to store the number of likes directly in each document of the playlist collection?
By doing this, I could update the number of likes for each playlist when a like is added or removed by creating an Appwrite function (on the server) triggered by databases.dev.collections.playlist_liked.documents..create or databases.dev.collections.playlist_liked.documents..delete. This way, I would update the count value, which avoids lengthy queries. So, my question is, is this the BEST way to do it and, more importantly, the most optimized way? On the contrary, are there any potential pitfalls? For example, if a user likes and unlikes a playlist multiple times rapidly in succession, will there be an inconsistency between the number of likes on the playlist document and the actual number of likes in the playlist_liked collection?
That's the example with playlists, but the same approach applies to the number of likes for a post, the number of followers, etc.
Thank you very much!