使用Firestore安全规则查询两个数组 [英] Querying with two array with firestore security rules
问题描述
我目前在一个文档中有两个数组,一个代表产品ID,另一个代表用户ID.在我的查询中,我需要查询两个数组以确保Firestore安全规则正常运行,但是要做到这一点,我尝试在同一数组中使用 array-contains
和 in
查询,这在文档中是可以接受的,但是当我查询时,我会得到缺少权限或权限不足".
I currently have two arrays in a single document, one representing product ids and the other representing user ids. In my query, I need to query both of the arrays for firestore security rules to work correctly, but to do that, I tried using array-contains
and in
in the same query, which is acceptable in the documentation, but when I go to query, I get "missing or insufficient permissions".
db.collection('Depots')
.where("products", "array-contains", productId)
.where("users", "in", "lk9asdn340fk3fvb")
.get();
这是我的安全规则:
function uidAndProductInDocument() {
return request.auth.uid in resource.data.users;
}
这是文档内容的样子:
但是,即使此安全规则失败,也不会返回任何内容,即使数据库中存在与参数匹配的文档也应返回.
However, even this security rule fails and does not return anything, even though there are docs in the database that should be returned, as they match the parameters.
我不确定如何确保产品关系,因为与产品用户的关系在另一个文档中,并且我在另一个问题中尝试了另一种方法,可以在这里找到: Firestore安全规则:在hasAny()列表方法中使用get()
I'm not sure how to secure the product relationship, as that relation for the product-user is in another document, and I have tried another approach in my other question, which can be found here: Firestore security rules: get() use in hasAny() list method
要使此查询正常工作,我需要做些什么吗?
Is there anything that I am missing or need to do for this query to work?
谢谢.
推荐答案
您应考虑重组数据以支持所需的查询.由于Firestore无法执行两个包含数组的查询,因此应将其中一个数组转换为对象,其中键是数组的值,而字段值只是 true
.例如,您可以获取您的用户列表,并使每个用户看起来像这样:
You should consider restructuring your data in order to support the query you need. Since Firestore can't perform two array-contains queries, one of your arrays should be converted to an object, where the keys are values of the array, and the field value is simply true
. For example, you could take your users list and make it look like this for each user:
users: {
xxxx: true
yyyy: true
}
现在您可以像这样查询:
Now you can query like this:
db.collection('Depots')
.where("products", "array-contains", productId)
.where(`users.${uid}`, "==", true)
.get();
您的规则可以像这样检查:
And your rule can check like this:
return resource.data.users[request.auth.uid]
这篇关于使用Firestore安全规则查询两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!