skip to Main Content

I’m attempting to perform a complex query with firestore v9. My intention is to get some docs (skip and limit) from a my data structure. What I mean is, I need to get for example 5 docs from a doc -> collections -> doc. and this docs need to be order by there date.

enter image description here
enter image description here

So for example, lets say in my array I contain 2 docs id ['e4z3HNyUCQbiYQRzfVO4RyebMCP2', 'WZImI6tl0IUFKbICEZzcciaUxKG2'], from this 2 docs, I would need to get their userPosts ordered by the creation date, but I would need to pass a skip and limit too. So from this 2 docs, I would limit 3 docs to get, but these 3 docs will be from the 2 posts ids I passed.

enter image description here

 const queryBuild = await query(
    collection(db, 'posts'),
    where('userPosts', 'in', [`post.id`...]),
    collection(db, 'userPosts'),
    ...
  );
  const querySnapshot = await getDocs(queryBuild);

2

Answers


  1. There is no out-of-the-box way to do what you are looking for with Firestore.

    You will need to issue two queries, one for each of the two parent document.


    Let say, for example, that in total you only want 3 documents from the two sub-collections.

    You first query the first subcollection with the following query:

    const q1 = query(collection(db, "posts/e4z3HNyUCQbiYQRzfVO4RyebMCP2/userPosts"), orderBy("creation", "desc"), limit(3));
    

    You then query the second subcollection with the following query:

    const q2 = query(collection(db, "posts/WZImI6tl0IUFKbICEZzcciaUxKG2/userPosts"), orderBy("creation", "desc"), limit(3));
    

    Then you merge the two results (i.e. push the documents of the two QuerySnapshots in one Array), order them by descending creation value and take the first three ones.

    Login or Signup to reply.
  2. An alternative to Renaud’s answer would be to store the postId of the parent document in each userPost. With that you could add an in clause to a collection group query to get the user posts of up to 10 parent documents.

    query(
      collectionGroup(db, "userPosts"), 
      orderBy("creation", "desc"), 
      where("parentPostId", "in", ["e4z3HNyUCQbiYQRzfVO4RyebMCP2", "WZImI6tl0IUFKbICEZzcciaUxKG2"]), 
      limit(3)
    );
    

    If you have more than 10 IDs, you’ll need to perform multiple of such queries, so you’d be back to a similar approach as in Renaud answers, just with 1/10th as many API calls.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search