我的集合中有 2 个字段,其中其他字段名为“uId”和“sellerUId”,如下面的屏幕截图所示。两者都是 Auth ID。我想过滤 uId == auth_id 或 sellerUId == auth_id。
我尝试了以下查询:
.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 不支持对多个字段进行 OR 查询。您需要 2 个不同的查询 - 一个针对 uid == auth_id
,另一个针对 sellerUid == auth_id
。
对于此用例,您可以在文档 users
中存储一个包含 userId
和 sellectUid
的数组,如下所示,这样您就可以得到在单个查询中获取这些文档:
{
users: ["uid", "sellerUid"],
...otherFields
}
然后你可以使用array-contains
运算符:
.doc('doc name')
.collection('collection name')
.where("users", arrayContains: "auth_id");
.get()
.then((QuerySnapshot querySnapshot) {
for (var doc in querySnapshot.docs) {
print(doc.id);
}
});
这将获取 users
数组包含 auth_id
的所有文档。您可以使用以下安全规则来确保这一点(假设 auth_id 是当前用户的 UID):
match /collection/{docId} {
allow read: if request.auth.uid in resource.data.users;
}
关于flutter - Firebase Firestore 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73776952/