如何检查字段是否存在Firestore规则?

时间:2020-05-22 10:27:27

标签: firebase google-cloud-firestore firebase-security

我有一个Firestore数据库,其中包含产品集合和类别集合。

仅当类别文档没有products字段时,我才希望向用户授予对类别集合的删除权限。

产品字段是参考数组。

我有以下规则:

match /shops/{shopId} {
  allow read: if true;
  allow write: if false;
  match /categories/{category=**}{      
    allow read: if true;
    allow write: if resource.data.products == null;
  }
}

但是此规则不起作用,我无法编写或更新文档。

2 个答案:

答案 0 :(得分:2)

尝试一下

match /shops/{shopId} {
  allow read: if true;
  allow write: if false;
  match /categories/{category=**}{      
    allow read: if true;
    allow create: if true;
    allow update, delete: if !('products' in resource.data);
  }
}

答案 1 :(得分:2)

使用如下帮助功能

function hasProducts(){
  return resource.data.keys().hasAny(["products"])
}

match /shops/{shopId} {
  allow read: if true;
  allow write: if false;
  match /categories/{category=**}{      
    allow read: if true;
    allow write: if !hasProducts();
  }
}
相关问题