这是可以完成的,但您首先必须将路径强制为字符串。
要获取当前资源的路径,可以使用__name__
财产。
https://firebase.google.com/docs/reference/rules/rules.firestore.Resource#name https://firebase.google.com/docs/reference/rules/rules.firestore.Resource#__name__
以供参考,resource
是一个通用属性,可用于表示正在读取或写入的 Firestore 文档的每个请求。
https://firebase.google.com/docs/reference/rules/rules.firestore.Resource https://firebase.google.com/docs/reference/rules/rules.firestore.Resource
resource['__name__']
返回的值__name__
是一个Path,缺少有用的方法,所以在使用之前size
您需要将路径强制为字符串。
https://firebase.google.com/docs/reference/rules/rules.String.html https://firebase.google.com/docs/reference/rules/rules.String.html
string(resource['__name__'])
转换为字符串后,您可以split
上的字符串/
运算符并将其转换为List
字符串路径部分。
https://firebase.google.com/docs/reference/rules/rules.String.html#split https://firebase.google.com/docs/reference/rules/rules.String.html#split
string(resource['__name__']).split('/')
现在您可以使用 List 检索列表的大小size
method.
https://firebase.google.com/docs/reference/rules/rules.List#size https://firebase.google.com/docs/reference/rules/rules.List#size
string(resource['__name__']).split('/').size()
Firestore 规则的挑战性之一是不支持变量,因此当您需要多次使用结果时,您经常会重复代码。例如,在这种情况下,我们需要使用分割的结果两次,但不能将其存储到变量中。
string(resource['__name__']).split('/')[string(resource['__name__']).split('/').size() - 2]
您可以通过使用函数并将参数用作变量来稍微干燥一下。
function getSecondToLastPathPart(pathParts) {
return pathParts[pathParts.size() - 2];
}
getSecondToLastPathPart(string(resource['__name__']).split('/'))
将它们结合在一起作为您的解决方案,它看起来像这样......
function getSecondToLastPathPart(pathParts) {
return pathParts[pathParts.size() - 2];
}
match test/{document=**} {
allow read, write: if getSecondToLastPathPart(string(resource['__name__']).split('/')) == 'subpath';
}
希望这可以帮助!