Firestore - 如何从 DocumentSnapshot 获取集合?

6
假设我有一个名为userSnapshot的变量,是通过执行get操作获取到的:
DocumentSnapshot userSnapshot=task.getResult().getData();

我知道可以从documentSnapshot中获取一个field,例如:

String userName = userSnapshot.getString("name");

它只是帮助我获取fields的值,但如果我想在这个userSnapshot下获取一个collection怎么办?例如,它的friends_listcollection包含朋友的documents

这个可能吗?

1个回答

11

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());
                }
            }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接