skip to Main Content

I was wondering if there is a way to make this code function another way around, so it finds all other records that do not contain this document reference?

Currently, I am building a list of records from the Users collection where I want to show only records that do not belong to some team.

I am using the ListView widget to display all records from the collection but I have a problem with filtering out users that have currently selected teams in their User document.
That User document contains a List of Document References to Teams Document Collection.

child: StreamBuilder<List<UsersRecord>>(
                  stream: queryUsersRecord(
                    queryBuilder: (usersRecord) => usersRecord.where(
                        'team_memberships',
                        arrayContains: widget.teamDocument!.reference),
              ),

I have tried a couple of things but I can not manage to do them so I am stuck.

2

Answers


  1. Try using whereNotIn

    Try this code:

    child: StreamBuilder<List<UsersRecord>>(
                      stream: queryUsersRecord(
                        queryBuilder: (usersRecord) => usersRecord.whereNotIn(
                            'team_memberships',
                            [widget.teamDocument!.reference]),
                  ),
    
    Login or Signup to reply.
  2. There is no way you can query Firestore for documents that don’t have a certain field or value. So you cannot query Firestore based on the absence of a particular value in an array.

    Firestore queries can only return documents based on values that so exist in the document. So a value on which you need to perform the query should exist in the first place. If a document doesn’t have a value for a specific field, it won’t be included in an index on that field, hence the impossibility of performing that query.

    Why is this not possible? This is because the number of non-existent values compared to what you already have in your database is extremely large. This means that Firestore cannot and should not create an index for all non-existing values. Querying for the non-existence of a value in an array would require a scan of all your documents, and that doesn’t scale.

    Perhaps you should also consider changing the array with a map:

    $docId (document)
      |
      --- team_memberships (map)
            |
            --- referenceOne: true
            |
            --- referenceTwo: false
    

    In this way, you’ll always have an index for each reference.

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