在地图包含字符串的Firestore查询 [英] Firestore query where map contains string
问题描述
数据结构:
houses (collection)
name (string)
users (map)
90c234jc23 (map)
percentage: 100% (string/number)
规则:
allow read: request.auth.uid in resource.data.users;
问题是当我尝试查询用户拥有的房屋时:
The problem is when I try to query houses which user owns:
FirebaseFirestore.getInstance().collection(House.COLLECTION)
// .whereArrayContains(House.USERS_FIELD, currentUser.getUid()) // does not work
.whereEqualTo("users." + currentUser.getUid(), currentUser.getUid()) // does not work either
.get()
没有结果返回.
推荐答案
由于不存在"map-contains-key"运算符,因此无法在firestore中执行此类查询.但是,有一种非常简单的解决方法,可以通过对数据结构进行细微调整来实现.
You cannot perform this type of query in firestore as there is no 'map-contains-key' operator. However, there are very simple workarounds for implementing this by making slight adjustments to your datastructure.
要求:要使该解决方案有效,每个地图值必须在Firestore查询中唯一标识,这意味着它不能是地图或数组.
Requirement: For this solution to work, each map value has to be uniquely identifyable in a firestore query, meaning it cannot be a map or an array.
如果您的案件符合列出的要求,则可以使用 @Dennis Alund的解决方案,其中建议使用以下数据结构:
If your case meets the listed requirements, you can go with @Dennis Alund's solution which suggests the following data structure:
{
name: "The Residence",
users: {
uid1: 80,
uid2: 20
}
}
常规解决方案
如果地图值是地图或数组,则需要为每个值添加一个属性,该属性在此类型的所有已创建值中将保持不变.这是一个示例:
General Solution
If your map values are maps or arrays, you need to add a property to each value which will be constant across all created values of this type. Here is an example:
{
name: "The Residence",
users: {
uid1: {
exists: true,
percentage: 80,
...
},
uid2: {
exists: true,
percentage: 20,
...
},
}
}
现在您可以简单地使用查询:
Now you can simply use the query:
_firestore.collection('houses').whereEqualTo('users.<uid>.exists', true)
这篇关于在地图包含字符串的Firestore查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!