如何在 Firestore 中对可选属性进行类型检查

How to type-check optional properties in Firestore

我不知道如何在 Firestore 中执行可选属性。它似乎没有包含在文档中,以下内容对我来说失败了。

service cloud.firestore {
  match /databases/{database}/documents {
    function maybeString(val) {
      return val == null || val is string
    }

    match /myCollection/{document} {
      function mySchema() {
        return request.resource.data.name is string
          && maybeString(request.resource.data.optionalProp);
      }

      allow read: if request.auth != null;
      allow create, update: if mySchema();
    }
  }
}


service cloud.firestore {
  match /databases/{database}/documents {
    match /myCollection/{document} {
      function mySchema() {
        return request.resource.data.keys().hasAll(['name'])
          && request.resource.data.name is string
          && request.resource.data.optionalProp is string;
      }

      allow read: if request.auth != null;
      allow create, update: if mySchema();
    }
  }
}

我正在使用第二种解决方案,但您需要使用 'fieldName' in resource.data.keys():

检查是否存在 optionalProp
service cloud.firestore {
  match /databases/{database}/documents {
    match /myCollection/{document} {
      function mySchema() {
        return request.resource.data.keys().hasAll(['name'])
          && request.resource.data.name is string
          && (
            ! ('optionalProp' in request.resource.data.keys())
            || request.resource.data.optionalProp is string
          );
      }

      allow read: if request.auth != null;
      allow create, update: if mySchema();
    }
  }
}