Home > Net >  Fetch firebase nested subcollections for multiple documents with 'where'
Fetch firebase nested subcollections for multiple documents with 'where'

Time:10-18

I'm creating a simple web application and want to fetch 10 particular posts replies at a time by their postIds.

I'm using Firebase firestore, here is my database design posts/{postDocument}/replies/{replyDocument}.

Reply here is a document inside a collection replies which contains into a document post

My use case is that I want to fetch 10 posts at a time and so for each post also its subcollection (replies)

If I do a loop like for each postDocumentId await fetchReplies(postDocumentId) it will take too much time for one iteration (10 iterations overall)

I want to achieve something like this:

  let postIds = [ '123', '321', '221','123', '021', '621','423', '521', '291','251' ]
  let snapshot = await firestore()
          .collection('posts/replies')
          .where('postId', 'in', postIds)
          .get();

In the end I want to get data from firebase the most optimal way and get it in this type:

[{post:{...},
replies:[{...},{...}]},
{post:{...},
replies:[{...},{...}]},
{post:{...},
replies:[{...},{...}]},
{post:{...},
replies:[{...},{...}]},
{post:{...},
replies:[{...},{...}]}]

Thank you in advance

CodePudding user response:

You can read documents from all replies collections with a collection group query.

But there's no way to limit that to the replies collections under a specific set of document IDs, unless those document IDs are also in the replies documents.

  • Related