我正在运行以下Firestore事务,以在accounts
集合中创建新文档,并将新创建的ID添加到用户accounts
。 (相反,发送到帐户的members
对象包含用户ID。)
db.runTransaction(transaction => {
return transaction.get(db.collection('accounts').doc())
.then(res => {
const accountId = res.id;
transaction.set(db.collection('accounts').doc(accountId), {name, numberOfEmployees, businessTypes, industry, members})
transaction.set(db.collection('users').doc(uid), {accounts: {[accountId]: true}}, {merge: true})
return accountId;
}, error => error)
})
我使用.collection('accounts').doc()
没有路径returns a new document这一事实,但我遇到了Missing or insufficient permissions.
错误。我的规则如下:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
match /accounts/{accountId} {
// allow read if user is a member or if the document does not exist
allow read : if resource.data.members[request.auth.uid] == true || !exists(/databases/{database}/documents/accounts/$(accountId));
// allow update, delete if user is a member
allow update, delete: if resource.data.members[request.auth.uid] == true;
// allow creation of any authenticated user
allow create: if request.auth != null;
}
}
}
我已将其缩小到read
上的/accounts/{accountId}
规则(如果我将其设置为if true;
,则可行)。我应该如何设置它以允许访问不存在的文档'了吗?
答案 0 :(得分:3)
通过将规则更改为:
找到答案allow read, update, delete: if request.auth != null && (resource.data.members[request.auth.uid] == true || resource == null);
答案 1 :(得分:1)
您可以在安全规则中使用getAfter()来获取文档状态,因为文档状态将在事务结束时(但在提交之前)。
因此,可以使用:
来代替resource == null
(对于阅读规则的人来说可能很奇怪)。
allow read, update, delete: if request.auth != null && getAfter(/databases/$(database)/documents/accounts/$(accountId)).data.members[request.auth.uid] == true;