【问题标题】:Unable to .getKey() after .add() to Cloud Firestore.add() 后无法 .getKey() 到 Cloud Firestore
【发布时间】:2018-04-18 01:46:39
【问题描述】:

我正在从 Firebase 实时数据库迁移到 Cloud Firestore。之前我会在实时数据库下.push(),得到.push()的key如下:

final String key = mBaseRef.child("ABC").push().getKey();

在新的 Cloud Firestore 下似乎没有此方法可用。我正在尝试这样:

mStoreBaseRef.collection("ABC").add(pollMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
    @Override
    public void onComplete(@NonNull Task<DocumentReference> task) {
        String key = String.valueOf(mStoreBaseRef.collection("ABC").document().getId());
        Log.v("KEY", key);
        Toast.makeText(getApplicationContext(),key,Toast.LENGTH_LONG).show();
    }
}

日志根本没有返回创建的密钥。

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    你可以先通过这段代码获取Id

     db = FirebaseFirestore.getInstance();
     String documentId=db.collection("MyCollection").document().getId();
    

    当你想为这个文档设置值时

    db.collection("MyCollection").document(documentId).set(myDataObject);
    

    【讨论】:

      【解决方案2】:

      你可以替换

      final String key = mBaseRef.child("ABC").push().getKey();
      

      DocumentReference key = db.collection("ABC").document();
      

      这将返回自动生成的 ID。 然后您可以稍后将其引用为:

      key.set(data);
      

      或者您可以将 Firebase 推送 ID 获取为:

      key.getId();
      

      【讨论】:

        【解决方案3】:

        对添加的文档的引用作为完成任务的结果返回。可以从中获得文档 ID:

            mStoreBaseRef.collection("ABC").add(pollMap)
                    .addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
                @Override
                public void onComplete(@NonNull Task<DocumentReference> task) {
                    if (task.isSuccessful()) {
                        DocumentReference docRef = task.getResult();
                        String key = docRef.getId();
                        Log.v("KEY", key);
                        Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
                    }
                }
            });
        

        【讨论】:

        • 非常感谢兄弟
        猜你喜欢
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 2020-09-29
        • 1970-01-01
        • 2021-08-23
        • 1970-01-01
        • 2018-09-15
        相关资源
        最近更新 更多