简体   繁体   English

Firestore:如何通过存在于其他集合中来过滤文档?

[英]Firestore: how to filter documents by existing in other collection?

For example, I want to get all users who is member of some "space".例如,我想获取属于某个“空间”的所有用户。

Simplified Firestore rule example:简化的 Firestore 规则示例:

match /users/{userId} {
  allow read: if exists(/databases/$(database)/documents/spaces/SPACEID/members/$(userId));
}

JS code in Web site:网站中的JS代码:

firebaseApp
    .firestore()
    .collection("users")
    .where( ??? )
    .onSnapshot((querySnapshot) => {
        ...
    });

I was able to come up with only 2 working options:我只能想出两个工作选项:

  1. Create spacesArray field in /users collection and use usersRef.where("spacesArray", "array-contains", "SPACEID") ./users集合中创建spacesArray字段并使用usersRef.where("spacesArray", "array-contains", "SPACEID") But in this case anyone can find out what groups the user is in by reading spacesArray .但在这种情况下,任何人都可以通过读取spacesArray来找出用户所在的组。 Also, the problem is that these arrays can be quite large, while this data is not needed on the client side, this causes excessive traffic.此外,问题在于这些数组可能非常大,而客户端不需要这些数据,这会导致流量过多。
  2. Get all members list in space first /databases/$(database)/documents/spaces/SPACEID/members/ and gets every user one by one.先获取空间中的所有成员列表/databases/$(database)/documents/spaces/SPACEID/members/并一一获取每个用户。 The problem with this option is that there can be a lot of users, every time the page is refreshed, hundreds or thousands of users will be requested via .get() or .onSnapshot() , which is redundant.这个选项的问题在于可能有很多用户,每次刷新页面时,都会通过.get().onSnapshot()请求成百上千的用户,这是多余的。

The ideal option would be to use an analogue of the exists(...) method from the rules in the where field, or somehow filter out spacesArray from the user's document for confidentiality purposes.理想的选择是使用where字段中的规则中的exists(...)方法的类似物,或者出于保密目的以某种方式从用户文档中过滤掉spacesArray

Firestore queries can only order/filter on data that is part of the documents the query returns. Firestore 查询只能对作为查询返回的文档的一部分的数据进行排序/过滤。 There is no way to order/filter on information in another document/collection.无法对另一个文档/集合中的信息进行排序/过滤。

So your exists check in the security rules is typically great for getting individual documents (known as get in the more granular security rules syntax), but not for handling bulk reads (known as list in granular security rules).因此,安全规则中的exists检查通常非常适合获取单个文档(在更细粒度的安全规则语法中称为get ),但不适用于处理批量读取(在细粒度安全规则中称为list )。

If you consider the list of spaces for a user private information, consider storing it in a UserSpaces collection, which (as you say in #2) leads to more reads, or consider storing only a one-way hash of the space in the public array.如果您考虑用户私人信息的空间列表,请考虑将其存储在UserSpaces集合中,这(如您在 #2 中所说)会导致更多读取,或者考虑仅存储公共空间的单向哈希大批。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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