如何解决从集合中获取文档数据-具有Firestore安全规则
我在Firestore中创建规则时遇到问题。
这是我的示例: 集合“用户”->许多文档-> 并非每个文档都在内部,名为“食谱”的子集合。 如果存在子集合“配方”,则它具有包含一些数据的文档。 其中之一是带有布尔类型的“ 公共”。
我的问题: 如果“公开”的条件为真,我想从所有用户那里获得所有食谱。
规则中的Im堆栈:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read: if request.auth != null && request.auth.uid == userId;
allow write: if request.auth != null && request.auth.uid == userId;
match /recipes/{recipeId} {
allow read: if resource.data.public == "true";
}
}
}
}
它向我显示:错误:Simulator.rules第[9]行,第[21]列。空值错误。
在这种情况下,如何使用干净的javascript获取/调用此数据? 如果我刚得到一些脚本,例如firebase.firestore()或firebase.auth()。
解决方法
对于他们正在寻找解决方案的人员。我找到一个! 让我解释一下:
- 我找到了https://firebase.google.com/docs/firestore/security/rules-query个有关查询规则的文档。
- 然后我决定使用
firebase.firestore().collectionGroup('recipes').get().then(...)...
- 我的安全代码如下:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{path=**}/recipes/{document} {
allow read: if resource.data.public == true;
}
}
}
- 我的JavaScript调用看起来像:
firebase.firestore().collectionGroup('recipes').where('public','==',true).get().then(recipes => {
recipes.forEach(doc => {
console.log(doc.data());
})
});
- 之后,我可以在console.log中看到错误:
AILED_PRECONDITION: The query requires an index. You can create it here
或熟悉链接的东西! - 我单击了链接,然后接受了collectionGroup的索引设置。
- 您也可以在这里找到它:
对不起,我的英语不好和Polskijęzyk很抱歉,但是我想我没错! 因此,它帮助我获得了在线公共食谱!
,您不能使用安全规则过滤结果。如果存在一个或更多违反该规则的文档,安全规则将阻止您的请求。您需要的是collection group queries。例如:
const querySnapshot = await db.collectionGroup('recipes').where('public',true).get();
querySnapshot.forEach((doc) => {
console.log(doc.id,' => ',doc.data());
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。