Firestore - 如何从 DocumentSnapshot 获取集合?

Tal*_*rda 5 java android firebase google-cloud-firestore

假设我有一个userSnapshot我已经使用的get操作:

DocumentSnapshot userSnapshot=task.getResult().getData();
Run Code Online (Sandbox Code Playgroud)

我知道我可以field从这样的 a 中得到 a documentSnapshot(例如):

String userName = userSnapshot.getString("name");
Run Code Online (Sandbox Code Playgroud)

它只是帮助我获得了 的值fields,但是如果我想获得一个collection低于 this 的值userSnapshot怎么办?例如,它friends_list collection包含documents朋友。

这可能吗?

Sam*_*ern 10

Cloud Firestore 中的查询很浅。这意味着当您get()创建文档时,您不会下载子集合中的任何数据。

如果要获取子集合中的数据,则需要进行第二次请求:

// Get the document
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();

            // ...

        } else {
            Log.d(TAG, "Error getting document.", task.getException());
        }
    }
});

// Get a subcollection
docRef.collection("friends_list").get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting subcollection.", task.getException());
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)