gpt4 book ai didi

java - Firestore - 如何从 DocumentSnapshot 中获取集合?

转载 作者:搜寻专家 更新时间:2023-11-01 08:24:21 24 4
gpt4 key购买 nike

假设我有一个 userSnapshot,我使用 get 操作获得了它:

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

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

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

它只是帮我获取字段的值,但是如果我想获取这个userSnapshot下的collection怎么办?例如,它的 friends_list collection 包含 friend 的 documents

这可能吗?

最佳答案

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

关于java - Firestore - 如何从 DocumentSnapshot 中获取集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com