Home > OS >  How to use Array contains in the same array fields in firebase for flutter
How to use Array contains in the same array fields in firebase for flutter

Time:11-07

I have a chat collection.

each document has an array with two user id's. my goal is to get the chat that has both user sys id's

I tried running the following but I got an error because we cant use two 'arrayContains' in one query.

Is there any way to perform such query?

here is an image of the data structure data structure

  Future getChat({required List userIdsArr}) async {
    var docId = '';

    userIdsArr.sort((a, b) {
      return a.compareTo(b);
    });
    var filter1 = userIdsArr[0];
    var filter2 = userIdsArr[1];
    await chat
        .where(userIdsArrayColumn, arrayContains: userIdsArr[0])
        .where(userIdsArrayColumn, arrayContains: userIdsArr[1])
        .get()
        .then((value) {
      value.docs.forEach((element) {
        docId = element.id;
      });
    });
    return docId;
  }

the goal is to get the chat that pertains to the users being passed in userIdsArr

CodePudding user response:

this seems to work, is there a better way of doing this?

 Future getChat({required List userIdsArr}) async {
    var docId = '';
    userIdsArr.sort((a, b) {
      return a.compareTo(b);
    });

    await chat
        .where(userIdsArrayColumn, arrayContains: userIdsArr[0])
        // .where(userIdsArrayColumn, arrayContains: userIdsArr[1])
        .get()
        .then((value) {
      value.docs.forEach((element) {
        if (element[userIdsArrayColumn].contains(userIdsArr[1])) {
          log('match found!');
          docId = element.id;
        }
      });
    });
    return docId;
  }

CodePudding user response:

A query can only contain a single array-contains query.

To allow your query, you'll want to add an additional field to the document where you keep the pair of UIDs in a predictable (e.g. alphabetical) order. With such a field you can then use a query such as:

where("concatenated_uids", isEqualTo: userIdsArr[0] "_"  userIdsArr[1])
  • Related