【问题标题】:About the Firestore query-data documentation specifically DocumentSnapshot关于 Firestore 查询数据文档,特别是 DocumentSnapshot
【发布时间】:2017-11-17 11:56:23
【问题描述】:

Firestore query-data get-data 文档中,我想知道document != null 在什么情况下会评估为假?不应该是!document.exists()

DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

【问题讨论】:

  • 我认为你是对的 - DocumentSnapshot 不应该是 null 但它可能不存在,所以这里应该使用 exists()Task 参考文档没有提到 getResult() 也可以返回 null
  • 事实上,除了 Android 和 Objective-C 之外,其他示例(重要的是 Java 示例)都使用 exists()
  • 刚开始迁移到 Cloud Firestore,如果文档正确,它会有所帮助,但我现在看到 CF 处于测试阶段,所以难怪

标签: android firebase google-cloud-firestore


【解决方案1】:

onComplete() 回调提供了一个 Task&lt;DocumentSnapshot&gt; 的 Google Task 实例,在此调用 getResult() 应该返回一个 DocumentSnapshot,而不是 null

这激起了我的兴趣,所以我做了一些测试:我将OnCompleteListener 附加到我知道不存在的文档中:

FirebaseFirestore.getInstance()
        .collection("this-does-not-exist")
        .document("neither-does-this")
        .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    if (task.getResult() == null) Log.d(TAG, "getResult is null");
                    Log.d(TAG, "getResult: " + task.getResult());
                }
            }
});

执行时,task.getResult() == null 检查评估为false,因此消息“getResult is null”写入日志。

但是,在从 getResult() 返回时调用 toString() 会引发以下错误:

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

这明确声明使用exists() 而不是空检查,但documentation for "get a document" 说:

注意:如果 docRef 引用的位置没有文档,则生成的 document 将为空。

此外,同一文档页面上其他语言的示例都使用exists(),但Android 和Objective-C 除外。最重要的是:Java 示例使用exists()

DocumentReference docRef = db.collection("cities").document("SF");
// asynchronously retrieve the document
ApiFuture<DocumentSnapshot> future = docRef.get();
// ...
// future.get() blocks on response
DocumentSnapshot document = future.get();
if (document.exists()) {
  System.out.println("Document data: " + document.getData());
} else {
  System.out.println("No such document!");
}

在这种情况下,我敢打赌这似乎是文档中的错误,我们应该使用document.exists() 而不是document != null

【讨论】:

猜你喜欢
  • 2021-02-18
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多