【问题标题】:Firestore: Creating a document with specified UID, eventually with set(), but without updating the fieldsFirestore:创建具有指定 UID 的文档,最终使用 set(),但不更新字段
【发布时间】:2019-07-07 15:46:41
【问题描述】:

考虑以下几行:

        Map<String, Object> the_data = new HashMap<>();
        the_data.put("login", "Anonymous");
        the_data.put("avatar_is_defined", false);
        the_data.put("amount", 0.0);
        the_data.put("deleted", false);
        the_data.put("can_read_user", true);
        Toast.makeText(this, "Initializing your data... Please wait until the screen appears.", Toast.LENGTH_SHORT).show();
        user_database_model.getReferenceToUser(signed_in_user_uid).set(the_data, SetOptions.mergeFields("")).addOnCompleteList[...]

用户第一次登录时,必须执行这个set调用,并且所有这些字段必须在UID为signed_in_user_uid的文档中实际设置。

但是,如果用户再次登录(即:文档已经存在),这个set要么必须被忽略(不执行)(实际上这是不可能的,见最后一段) , 或者它的字段不能被更新(这就是我写SetOptions.mergeFields("")没有成功的原因)。

是否可以调用set 函数说“Firestore,如果它不存在,请创建此文档并用提供的字段填充它;但如果它已经存在,只是......不要'什么都不做”?

重要提示:由于 Firestore 安全规则,我无法get() 知道该文档是否存在。 (在回调中我会调用set,只有当它不存在时)。所以避免调用set(不执行它)实际上是不可能的。

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    如果您只希望用户能够创建他们的文档一次,并且永远不会更新它,您可以在安全规则中这样做:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{uid} {
          // Applies to writes to nonexistent documents
          allow create: if request.auth.uid != null;
    
          // Reject writes to existing documents
          allow update: if false;    
        }
      }
    }
    

    如果您希望客户端代码检测文档是否已存在,如果不存在则创建它,use a transaction

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 2021-02-28
      • 2020-10-01
      相关资源
      最近更新 更多