Home > Enterprise >  Firebase firestore query
Firebase firestore query

Time:09-21

I have 2 fields with other fields named 'uId' and 'sellerUId' in my collections as in the screenshot below. Both are Auth IDs. I want to filter uId == auth_id or sellerUId == auth_id.

enter image description here

I have tried the following query:

.doc('doc name')
  .collection('collection name')
  .where(['uId', 'sellerUId'], isEqualTo: 'auth_id')
  .get()
  .then((QuerySnapshot querySnapshot) {
    for (var doc in querySnapshot.docs) {
      print(doc.id);
    }
  });

CodePudding user response:

Firestore does not support OR queries on multiple fields. You would need 2 different queries - one for uid == auth_id and another for sellerUid == auth_id.

For this use case, you can store a single array in the document users that contains both userId and sellectUid like this so you get fetch these documents in a single query:

{
  users: ["uid", "sellerUid"],
  ...otherFields
}

Then you can use array-contains operator:

.doc('doc name')
  .collection('collection name')
  .where("users", arrayContains: "auth_id");
  .get()
  .then((QuerySnapshot querySnapshot) {
    for (var doc in querySnapshot.docs) {
      print(doc.id);
    }
  });

This will fetch all documents where the users array contains auth_id. You can secure this with the following security rules (assuming auth_id is UID of current user):

match /collection/{docId} {
  allow read: if request.auth.uid in resource.data.users;
}
  • Related