我有一个具有以下规则的 Firestore 数据库:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null && request.auth.uid == resource.data.uid;
allow create: if request.auth != null && request.auth.uid == request.resource.data.uid;
}
}
}
查询一组文档时,我需要在查询中包含
uid
以满足规则并且它有效:
try await db.collection("Stocks")
.whereField("uid", isEqualTo: user.uid) // Include the uid for passing the rule
.getDocuments()
但是,对于数据库中不存在的文档的单文档查询,会返回权限错误:
let document = try await db.collection("Stocks")
.document(stock.id) // The document does not exist in the database
.getDocument()
if document.exists {
} else {
}
我该如何定义这种情况的规则?
我的期望是,如果 stock.id 不存在,Firestore 应该返回 nil 或空结果,对吗?
不,事情不是这样的。
getDocument
尝试完整阅读文档,即使您的代码仅继续检查它是否存在。
安全规则可防止客户了解任何与规则不完全匹配的文档。 您收到权限错误是因为您尝试获取不符合规则的文档,无论该文档是否存在。