[英]Firestore - How Can I Get The Collections From a DocumentSnapshot?
Let's say I have a userSnapshot
which I have got using get
operation: 假设我有一个使用
get
操作get
的userSnapshot
:
DocumentSnapshot userSnapshot=task.getResult().getData();
I know that I'm able to get a field
from a documentSnapshot
like this (for example): 我知道我可以像这样从
documentSnapshot
获取field
(例如):
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
? 它只是帮助我获取
fields
的值,但是如果我想在此userSnapshot
下获取collection
userSnapshot
办? For example, its friends_list
collection
which contains documents
of friends. 例如,它的
friends_list
collection
包含朋友的documents
。
Is this possible? 这可能吗?
Queries in Cloud Firestore are shallow. Cloud Firestore中的查询很浅。 This means when you
get()
a document you do not download any of the data in subcollections. 这意味着当您
get()
文档时,您不会下载子集合中的任何数据。
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());
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.