Firebase Cloud Firestore:无效的集合引用.集合引用必须具有奇数个段

Rel*_*elm 32 java android firebase google-cloud-firestore

我有以下代码并收到错误:

Invalid collection reference. Collection references must have an odd number of segments
Run Code Online (Sandbox Code Playgroud)

和代码:

private void setAdapter() {
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        db.collection("app/users/" + uid + "/notifications").get().addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                for (DocumentSnapshot document : task.getResult()) {
                    Log.d("FragmentNotifications", document.getId() + " => " + document.getData());
                }
            } else {
                Log.w("FragmentNotifications", "Error getting notifications.", task.getException());
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

Die*_*cio 33

然后你需要改变这个:

db.collection("app/users/" + uid + "/notifications")...
Run Code Online (Sandbox Code Playgroud)

为了这:

db.collection("app").document("users").collection(uid).document("notifications")
Run Code Online (Sandbox Code Playgroud)

没关系 ;)


Bob*_*der 27

文档中描述了分层数据结构和子集合.集合包含文档,文档可能包含子集合.结构始终是集合和文档的交替模式.该文档包含一个示例的描述:

注意集合和文档的交替模式.您的馆藏和文档必须始终遵循此模式.您无法在集合中引用集合或在文档中引用文档.

因此,集合的有效路径将始终具有奇数个段; 文档的有效路径,偶数.由于您的代码正在尝试查询集合,因此路径长度为4无效.

  • 并不是说其他​​人会愚蠢到会错过这一点,而是可以导致此错误的另一种简单方法是,如果对空白文档引用运行get,请检查变量并确保其不是空字符串。 。 (3认同)

小智 6

您缺少集合参考。即 db.collection(** 这将变为 null **)。