0

I have posts for a group chat stored in an array. I'm trying to get the newest posts to be shown at the top and the oldest at the bottom. I'm not sure what to do or how I could maybe get new posts to be [0] in the array.

Below is the Firestore schema.

enter image description here

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 2
    You're going to have to write code to sort the posts array after you read the document, then write that sorted array back to the document if that's what you want. Firestore won't do this for you. – Doug Stevenson Sep 29 '22 at 22:19
  • 1
    It is better you use sub collection and `orderBy` `timestamp` when fetching. – Peter Obiechina Sep 29 '22 at 22:24
  • Hey Mr. Stevenson do you have any recommendations or way to show me how to write that code? –  Sep 30 '22 at 00:19

2 Answers2

1

You can use post.insert(0,...) (when adding to the list that way it's easier to sort without any function)

In the code above post is your List/arry name, then same way you call .add to a List you can call .insert(0,...) where the "0" is your index.

so what it does is, it inserts every new item to the List at "Index 0" which "0" is the first position in any List, Map or array

Britchi3
  • 180
  • 5
  • 17
  • hey britchi, i tried your solution but when i did it still put the posts at the bottom. Plus it added the "post" twice –  Oct 02 '22 at 00:50
0

I recently answered a similar question, where I provided a recommendation to use arrays for comments that correspond to a particular post. Now, when it comes to sorting, as Doug mentioned in his comment, Firestore doesn't have that capability. There is no mechanism present that can sort the objects within an array. You need to write some code yourself that does that. How? By simply reading the document, read the posts array, do the sorting in memory and then write the document containing the sorted array back to Firestore.

If you find yourself in a position where you need to update an object within an array of objects, then I recommend you check the following article:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193