You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase Rules中设置正确的文档名称校验规则?

解决Firestore仅允许创建特定名称文档的规则配置问题

问题分析

你之前的尝试失败主要源于对request.resource.__name__的格式理解偏差,以及规则方法的使用场景不匹配:

  1. hasAny会检查路径数组中是否包含指定字符串,而非精确匹配文档名称,容易误判路径中其他位置出现相同字符串的情况
  2. matches('.*someDocument')仅匹配路径中存在该字符串的情况,未锚定结尾,无法确保是文档名称本身
  3. 精确对比时使用了URL编码后的路径(%28default%29),但request.resource.__name__返回的是未编码的原始路径((default)),导致对比不成立

正确规则配置方案

方案1:允许任意路径下创建名称为someDocument的文档

适用于需要在所有集合中限制文档名称的场景,通过split('/').last()获取路径最后一段(即文档名称)进行精确匹配:

service cloud.firestore 
{
  match /databases/{database}/documents
  {
    match /{document=**}
    {
        allow read: if true;
        allow write: if request.resource.__name__.split('/').last() == 'someDocument';
    }
  }
}

方案2:使用正则表达式匹配文档名称结尾

通过正则锚定符$确保路径最后一段是目标文档名称:

service cloud.firestore 
{
  match /databases/{database}/documents
  {
    match /{document=**}
    {
        allow read: if true;
        allow write: if request.resource.__name__.matches('.*/someDocument$');
    }
  }
}

方案3:指定特定集合下的文档名称限制(推荐)

如果仅需限制某个集合下的文档名称,更推荐明确匹配路径,规则更清晰且性能更优:

service cloud.firestore 
{
  match /databases/{database}/documents
  {
    match /someCollection/{docId} {
        allow read: if true;
        allow write: if docId == 'someDocument';
    }
    // 可添加其他路径的规则配置
  }
}

内容的提问来源于stack exchange,提问作者ILurch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:00:56