我想查询文档引用以查看文档当前是否存在。如果它不存在,那么我想为该引用编写一个新文档。
不幸的是,这不符合我的安全规则。如果文档确实已经存在,那么我只希望授权人员能够查看它。我的规则是这样的
Firestore 规则
function getItemData(item){
return get(/databases/$(database)/documents/equipment/$(item)).data;
}
function getUserData(){
return get(/databases/$(database)/documents/users/$(request.auth.uid)).data;
}
match /equipment/{item}{
allow create: if request.auth != null;
allow read: if !exists(/databases/$(database)/documents/equipment/$(item)) ||
getUserData().clientId == getItemData(item).clientId;
}
文档结构
users > userId: {
clientId: "idhere"
}
equipment > item: {
clientId: "idhere",
serial: "serialnumber"
}
我执行获取请求的 native 代码
const docRef = firestore.collection("equipment").where('clientId', '==', clientId).where("serial", "==", serial);
docRef.get().then(doc => {
if(!doc.exists){
//add new item to existing document reference
}
}).catch(error => {
//Error here reads "Missing or insufficient persmissions"
})
如果我直接查询它们,我可以读取它们。但是,我的 where() 函数似乎与规则冲突。
有人知道为什么会这样吗?
编辑:如果我将规则更改为此
match /equipment/{item}
allow read: if true
我找到了成功,所以我确定是这条规则导致了我的问题。使用模拟器时,我可以直接访问文档。问题似乎出在 where 语句上
最佳答案
对于结果集中的每个文档,您似乎希望规则检查其他文档的内容是否表明它应该是可读的。查询失败,因为 security rules are not filters .请务必理解此处的文档。您不能编写从请求的结果集中删除文档的规则 - 查询必须是全有或全无。
该规则适用于文档 get() 请求,因为请求的文档是提前已知的 - {item}
具有特定值。但在查询的情况下,规则无法单独检查每个可能的文档。您需要找到另一种方式来表达您的意图。
关于javascript - Firestore规则-查询文档是否存在-权限不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58377145/