Yassine Bridi
Yassine Bridi

Reputation: 923

How can i get sub-collections of sub-collections in Firebase in one call

I have a firebase schema that look like this: posts > posts(documents) > comments > comments(collections) > replies > replies(documents)

const allComments = await firebase
  .collection('posts')
  .doc(params.slug as string)
  .collection('comments')
  .orderBy("date", "desc")
  .get()

if i tried to get the reply like this:

const allComments = await firebase
  .collection('posts')
  .doc(params.slug as string)
  .collection('comments')
  .doc("some_random_id")
  .collection('reply')
  .get()

i will get only the reply, which is not the desired output. i need to get each reply of each comment in one call. so the returned object would be every comment, and each comment contains an object of replies.

Upvotes: 1

Views: 326

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Firestore queries are "shallow", and only return documents immediately within the collection being queried. They don't consider any documents from subcollections. To get documents from subcollections, you would need to make another query for each subcollection.

It might be better to simply put all the comments and replies in a single collection, mark them each with a boolean indicating if it's a reply or not, and use that as a filter if needed on the query. The size of the collection will not have any impact on performance.

Upvotes: 2

Related Questions