Ad

How Can I Make Sure To Fetch Only The X Most Recent Posts In DB?

I am trying to fiigure out how exacly I should make sure that I only fetch the most recent x posts from the DB.

My current fetch methods work as follows:

GetPeopleIFollowAnd loop over each UID
        For each UID fetch his posts

By doing this however I cant efficiently (quickly) fetch only the most recent x posts. How can I do this?

Some possible ideas I have:

  • Create a new Node which, every time that one of your followers makes a post, they will be added beneath your UID with a timeStamp. So When I fetch I loop through this FollowersWhoCreatedRecently for each UID and only do so for the first 10

Problems I see with the above solution is that if a user were to have a millions of people following them this would be horribly slow when it comes to updating every single one of those million

I have found this which seems like it may be of use. How could I use this?

My DB structure for posts is as follows

Post
  UID
    postID
       Media
          media
             image: URL

Based in a follower structure like:

WhoFollowsMeNode/UID/uid: true

I would have to, every time a user posts, loop through this list where for each user I would add the post to there timeLine... That seems undoable, and yet that what it seems they are doing here.

Ad

Answer

On Realtime Database, you can make use of limitToLast() method, you can then pass how many elements you want to bring, this method will fetch the last information that has been added in a node, since the documents are ordered with a timestamp, if you fetch them with limitToLast(10) you can get the last 10 posts of a user.

If you are working with a List of posts, you can invert the list when showing it to the user, doing this, you will see the most recent data first and the old data below.

Ad
source: stackoverflow.com
Ad