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

Sar*_*Vin 5 firebase firebase-security google-cloud-firestore

我有一个包含产品集合和类别集合的 firestore 数据库。

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

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

l1b*_*rty 8

尝试这个

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);
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用辅助函数如下

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();
  }
}
Run Code Online (Sandbox Code Playgroud)