0

I have a collection containing posts which are documents containing a timestamp and other data, we could call it global post object. Whenever an user posts something, a document with the same id as the post id is added to the user's private post collection (under users/userUuid/posts/postId), let's call it private post object. Each private post object contains a reference to the global post object (stored as a reference object in the document). This is the structure:

posts: [
    "post1" : {
        timestamp: 12000000000
        data: "abc"
        
    }
    "post2" = {
        timestamp: 12000000000
        data: "abc"
        
    }
]

users: [
    "user1" : {

        posts: [
            "post1": {
                ref: reference to post1
            }
        ]
    }
] 

I have a screen in which I'm querying all the objects under the user's private post collection. Is it possible to sort those based on the timestamp value of the document they reference?

Fabrizio
  • 1,138
  • 4
  • 18
  • 41
  • You are trying to sort the post of users collection individually based on posts collection timestamp? Is that correct? – JM Gelilio Jul 29 '21 at 01:00
  • @JMGelilio Yes, exactly, so the feature I would like to use to sort the documents is a timestamp in a document which is just referenced in the document I'm trying to sort. – Fabrizio Jul 29 '21 at 11:28

1 Answers1

0

Is it possible to sort those based on the timestamp value of the document they reference?

It seems you are trying to join the two data from two collection in Cloud/Firebase Firestore which is faster if there's a join queries but Firestore has no join queries. There are still ways but they do it differently, most cases they perform multiple read operations, store in array variable and sort it or using collection group query. It still depend on your codes and how you will handle the data, there are some questions that already explain it in multiple questions in Stack Overflow(ex. 1, 2).

I would suggest that it will be easier if you change your Firestore data structure. For example, add field(ex. author) that has a value of userid(ex. users1) to the posts collection so every post has an owner. Use where clause for author field and orderBy clause for timestamp field to sort it desc or asc:

structure:

posts: [

    "post1" : {
    
        timestamp: 12000000000
        data: "abc"
        author: "user1"

    }
    
    "post2" = {
    
        timestamp: 12000000000
        data: "abc"
        author: "user1"
        
    }
    
]
JM Gelilio
  • 3,482
  • 1
  • 11
  • 23