如何从文档快照获取集合

如何从文档快照获取集合

本文介绍了Firestore - 如何从文档快照获取集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  DocumentSnapshot userSnapshot = task.getResult()。getData(); 

我知道我可以得到字段 documentSnapshot )(例如):

pre $ String userName = userSnapshot.getString(name);

它只是帮我获取字段的值,但是如果我想在 userSnapshot 下面得到一个集合?例如,其 friends_list 集合其中包含文档的好友。



这可能吗?

解决方案

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

想要获得子集合中的数据,你需要做第二个请求:

pre code获取文档
(@NonNull Task< DocumentSnapshot>任务){
if(task.isSuccessful() ){
DocumentSnapshot document = task.getResult();

// ...

} else {
Log.d(TAG,获取文档时出错。,task.getException());
}
}
});
$ b $ //获取子集合
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());
}
}
});


Let's say I have a userSnapshot which I have got using get operation:

DocumentSnapshot userSnapshot=task.getResult().getData();

I know that I'm able to get a field from a documentSnapshot like this (for example):

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

It just helps me with getting the values of the fields, but what if I want to get a collection under this userSnapshot? For example, its friends_list collection which contains documents of friends.

Is this possible?

解决方案

Queries in Cloud Firestore are shallow. This means when you get() a document you do not download any of the data in subcollections.

If you want to get the data in the subcollections, you need to make a second request:

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

这篇关于Firestore - 如何从文档快照获取集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:35