简体   繁体   中英

Firebase firestore query

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 .

在此处输入图像描述

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);
    }
  });

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM