skip to Main Content

Using firebase-admin, I have several collections inside one collection. I need them all, so I need to to 4 different calls. The first one for the "users" collection, and the other 3 are the children of "users":

  const profile = await admin
    .firestore()
    .collection("users")
    .doc(context.auth.uid)
    .get();

  const internProps = await admin
    .firestore()
    .collection("users")
    .doc(context.auth.uid)
    .collection("internProps")
    .get();

  const externProps = await admin
    .firestore()
    .collection("users")
    .doc(context.auth.uid)
    .collection("externProps")
    .get();

  const geoPath = await admin
    .firestore()
    .collection("users")
    .doc(context.auth.uid)
    .collection("geoPath")
    .get();

Making 4 calls to the DB sounds expensive.. Is it possible to somehow call only the "users" and extract the children collections from it? Or there is no other way than calling the other 3 methods :/

2

Answers


  1. Is it possible to somehow call only the "users" and extract the
    children collections from it?

    It is not possible, with one query, to get documents from a parent collection and children collections of this parent collection.

    The reason is that, from a technical perspective, a parent collection and the sub-collections of the documents in this parent collection are not at all related to each other.

    Let’s take an example: Imagine a doc1 document under the col1 collection

    col1/doc1/
    

    and another one subDoc1 under the subCol1 (sub-)collection

    col1/doc1/subCol1/subDoc1
    

    These two documents (and the two immediate parent collections, i.e. col1 and subCol1) just share a part of their path but nothing else.

    So you’ll need to issue four queries, one for each (sub-)collection.

    Login or Signup to reply.
  2. What you ask for can’t be done with firebase.

    However, if your concern is number of calls that are being made, consider making using a map instead of a subcollection. This way you can get all data with a single request

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