[英]Firestore rules - How to allow create but not update?
Here's what I've written;这是我写的;
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /reservedUsernames/{username} {
allow update: if false;
allow create: if request.auth != null;
}
}
}
I already added a document with ID sam
and a field userId
= 122
.我已经添加了一个 ID 为
sam
和一个字段userId
= 122
的文档。 If I run an update on that document, see how below, it succeeds?如果我对该文档运行更新,请参阅下面的内容,它会成功吗? How can I allow creations but no updates?
如何允许创建但不允许更新?
db.collection("reservedUsernames")
.document(searchableUsername)
.setData(["userId": userId])
When using:使用时:
.setData(["userId": userId])
It means that you're setting the data, and not updating it.这意味着您正在设置数据,而不是更新它。 The following rule:
以下规则:
allow update: if false;
Indeed rejects all update operations but as @DougStevenson mentioned in his comment, having it in your rules it's the exact same thing as not having it at all, because by default the rules are set to false.确实拒绝所有更新操作,但正如@DougStevenson 在他的评论中提到的那样,将它包含在您的规则中与根本没有它完全相同,因为默认情况下规则设置为false。
I managed to do it by using Security Rules:我设法通过使用安全规则来做到这一点:
rules_version = '2'
service cloud.firestore {
match /databases/{database}/documents {
match /reservedUsernames/{documentId} {
allow create: if request.auth != null && existingData(resource) == null
}
function incomingData(request) {
return request == null || request.resource == null || request.resource.data == null ? null : request.resource.data
}
function existingData(resource) {
return resource == null ? null : resource.data
}
}
}
This way I check if I'm updating an existing document and it passes only if I'm not!通过这种方式,我检查我是否正在更新现有文档,并且只有在我没有更新的情况下才会通过!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.