【问题标题】:Firebase Cloud Firestore follow referenceFirebase Cloud Firestore 遵循参考
【发布时间】:2018-05-11 00:56:23
【问题描述】:

我收到了queryDocumentSnapshot,代码如下:

mFireStore = FirbaseFirestore.getInstance();
mFireStore.collection("myCollection").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
                    if (doc.getType() == DocumentChange.Type.ADDED) {
                        // Set some data from the doc.getDocument here

mFireStore.collection("myCollection").document(doc.getDocument().getId()).collection("subCollection").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                                    @Override
                                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                                        if (queryDocumentSnapshots.isEmpty()){
                                            // not found
                                        } else{

                                            List<DocumentSnapshot> hosts = queryDocumentSnapshots.getDocuments();

                                            for (int i = 0; i < hosts.size(); i++){
                                                // Each hosts DocumentSnapshot has a "host" field which contains a reference to a document
                                                // I'd like to follow this reference and get that document
                                            }
                                        }
                                    }
                                });

我的问题是,一旦我获得了主机DocumentSnapshots 的列表,我想关注他们的“主机”字段,其中包含对文档的引用。我想遵循此参考并在另一端获取文档,但不知道如何。如果您发现我的逻辑有任何其他问题,请随时指出,因为我是 Cloud Firestore 的新手。

【问题讨论】:

  • 将这些主机id存储在一个数组中,然后开始监听每个id
  • 如果你想达到这个目的,你需要NestedQueries,因为你应该对你的“关注”用户中的每个文档进行一次查询。另一种方法是执行一个云功能,将该用户的帖子复制到关注它的用户的“提要”,这样您就可以始终查询提要,并避免嵌套查询

标签: java android firebase google-cloud-firestore


【解决方案1】:

要解决这个问题,您可以简单地遍历 hosts 列表。如果您的host 字段将引用保存为String,则请使用以下代码行:

for (DocumentSnapshot ds : hosts) {
    String host = ds.getString("host");
    Log.d("TAG", host);
}

如果您的 host 字段将引用保存为 DocumentReference,请使用以下代码行:

DocumentReference host = ds.getDocumentReference("host");

【讨论】:

  • 一切都好吗?您是否尝试过我上面的解决方案?
猜你喜欢
  • 2021-03-25
  • 2018-08-02
  • 2021-07-10
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多