Home > Back-end >  How to order comments in firebase firestore by createdAt
How to order comments in firebase firestore by createdAt

Time:05-07

I have a document in which there is a comments array of objects and each object has createdAt property. I want to sort all the comments that are inside the comments array using the createdAt property, so, a new comment comes to the top.

I did some research and found that we can do this in enter image description here

CodePudding user response:

The query() function takes a query as parameter and not a DocumentReference. Also the orderBy() clause orders documents when fetching multiple documents from a collection and not array elements.

To order array elements, you first need to fetch that document and then manually sort the array.

const unsubscribe = onSnapshot(
  docRef,
  (snapshot) => {
    // need to make sure the doc exists & has data
    if (snapshot.data()) {
      const orderedArray = snapshot.data().comments.sort((a, b) => a.createdAt.seconds - b.createdAt.seconds);
    } else {
      setError("No such document exists")
    }
  }
)
  • Related