Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Firestore : Invalid collection reference. Collection references must have an odd number of segments

I have the following code and getting an error :

Invalid collection reference. Collection references must have an odd number of segments

And the code :

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());
            }
        });
    }
like image 945
Relm Avatar asked Oct 09 '17 04:10

Relm


2 Answers

Then you need replace it:

db.collection("app/users/" + uid + "/notifications")...

with it:

db.collection("app").document("users").collection(uid).document("notifications")

You're welcome ;)

like image 145
Diego Venâncio Avatar answered Nov 05 '22 22:11

Diego Venâncio


Hierarchical data structures and subcollections are described in the documentation. A collection contains documents and a document may contain a subcollection. The structure is always an alternating pattern of collections and documents. The documentation contains this description of an example:

Notice the alternating pattern of collections and documents. Your collections and documents must always follow this pattern. You cannot reference a collection in a collection or a document in a document.

Thus, a valid path to a collection will always have an odd number of segments; a valid path to a document, an even number. Since your code is trying to query a collection, the path length of four is invalid.

like image 60
Bob Snyder Avatar answered Nov 05 '22 22:11

Bob Snyder