Search code examples
firebasegoogle-cloud-firestoreangularfire

Firestore collection group query on document id


I am trying to run the following query:

this.db.firestore
        .collectionGroup('members')
        .orderBy('dateModified', 'desc')
        .where(firebase.firestore.FieldPath.documentId(), '==', uid)

But I get the error:

Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but 'X6yL5Ko55jSMWhhoQUO91xVYdEH3' is not because it has an odd number of segments (1).

Is the only way around this to add the document id to the document? This is not ideal as I have a lot of existing data... The document id is the uid of the firebase user.


Solution

  • Adding the uid to the document itself is the only possible way at the moment and then query on that field:

    this.db.firestore
            .collectionGroup('members')
            .orderBy('dateModified', 'desc')
            .where("uid", '==', uid)
    

    There was a Github issue for the same and explains why that's not possible.

    That's pretty much why I sometimes prefer to store a root level collection members. Each document in the collection will have contain the groupID (or whatever your parent collection is meant for). If you use userID as the key for documents in there then it goes easy.

    this.db.firestore.collection("members").doc(uid)
    

    So instead of having a path like: /groups/{groupID}/members/{memberID}, the structure will be like: /groups/{groupID} and all the members will be store in the root level collection 'members'. A document in that collection may look like:

    // uid as doc key
    {
      groupId: "groupID", 
      ...otherFields
    }
    

    The catch is if a member can join multiple groups you cannot use the userId as the key.