【问题标题】:How to query a collection to get specific documents?如何查询集合以获取特定文档?
【发布时间】:2020-09-23 17:22:23
【问题描述】:

我将开始使用示例来解释我的问题,我有 2 个名为 Users 和 Foods 的根集合。 在用户集合中,包含具有用户信息的文档,例如名称、图像和年龄。在foodsCollection 中,包含具有诸如Food_name、成分和图像等字段的文档。现在我想让用户根据自己的意愿为食物添加书签。因此,我在名为 Bookmark 的用户文档中再创建一个集合,并将 Food 文档的 Id 保存在 Bookmark 集合的文档中。现在我想使用保存的食物文档 ID 获取唯一的书签文档。我将编写我的数据结构以供进一步理解。


 Foods(Collection) ----1ztEzZLkTp5XOZzsoYRL(Feilds--Name,Image,Ingradents,Document_Id)
                 
                  ----4Q6k0MifwEyoLs8rgZbs(Feilds--Name,Image,Ingradents,Document_Id)
                
                  ----870BEaDFMkMWTi4VaXmh(Feilds--Name,Image,Ingradents,Document_Id)
                  [...]

 Users(Collection)----User1(Document)----Bookmarks(Collection)----RandomId("Bookmarked_Doc_Id" - 1ztEzZLkTp5XOZzsoYRL)
                                                              ----RandomId("Bookmarked_Doc_Id" - 870BEaDFMkMWTi4VaXmh)
    
                  ----User2(Document)----Bookmarks(Collection)----RandomId("Bookmarked_Doc_Id" - 1ztEzZLkTp5XOZzsoYRL)
    
                  [...]

现在我想使用 Bookmarked_Doc_Id 获取 Food 集合的文档数据

例如,当用户1点击书签选项卡时,他可以看到2个书签,其名称、图像和ingradents。

如何存档?

编辑

 rootRef.collection("Users").document(USER_ID).collection("Bookmarks").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()){
                    for (DocumentSnapshot document : task.getResult()){
                        if (document.exists()){
                            String getDocuments = document.get("Bookmark_Document_Id").toString();
                            loadBookmarks(getDocuments);
                            Log.d(TAG, "onComplete: "+" "+getDocuments);
                        }
                    }
                }
            }
        });
  private void loadBookmarks(String getDocuments) {
    Query query = FirebaseFirestore.getInstance().collection("Foods").whereEqualTo("Document_Id",getDocuments);
    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(2)
            .setInitialLoadSizeHint(2)
            .setPageSize(3)
            .build();

    FirestorePagingOptions<FoodItems> options = new FirestorePagingOptions.Builder<FoodItems>()
            .setQuery(query, config, FoodItems.class)
            .build();

    food_items_recycle_adapter = new Food_Items_Recycle_Adapter(options, progressIndicator,null);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setAdapter(food_items_recycle_adapter);
    food_items_recycle_adapter.notifyDataSetChanged();
    food_items_recycle_adapter.startListening();
}

此代码仅显示最新添加的书签,而不是显示所有书签。

【问题讨论】:

  • 请编辑问题以显示您尝试过的代码未按您预期的方式工作。如果您不知道如何使用其 ID 获取文档,我建议您从 documentation 开始。
  • @DougStevenson 我编辑了我的问题。
  • @DougStevenson 我有一个想法,当用户点击书签按钮时,我可以将整个食物文档保存在用户的书签集合中,但是如果有人更改了原始食物文档数据,用户的书签文档数据不会改变。
  • 您可能想在您的问题中更详细地解释具体问题。简单地问“可能吗?”不是一个很明确的问题。绝对可以通过其 ID 获取文档。我们需要知道您对此有何具体问题。
  • 如果您在使用 Firebase UI 时遇到问题,您可以自己进行分页!参考这里:Firestore Pagination

标签: android firebase google-cloud-firestore


【解决方案1】:

最后,我解决了我的问题,这就是我想要的:)

enter code here  final FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user!=null){
        String USER_ID = user.getUid();

        rootRef.collection("Users").document(USER_ID).collection("Bookmarks")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                        if (error!=null){
                            Log.w(TAG, "Listen failed.", error);
                            return;
                        }
                        List<String> foodlist = new ArrayList<>();
                        assert value != null;
                        for (QueryDocumentSnapshot doc : value) {
                            if (doc.get("Bookmark_Document_Id") != null) {


                                foodlist.add(doc.getString("Bookmark_Document_Id"));
                                Log.d(TAG, "Food items are: " + foodlist);
                               
                                Query query = rootRef.collection("Recipes").document("Food_Recipe").collection("Powder_Recipe").whereIn("Document_Id",foodlist);
                                PagedList.Config config = new PagedList.Config.Builder()
                                        .setEnablePlaceholders(false)
                                        .setPrefetchDistance(2)
                                        .setInitialLoadSizeHint(2)
                                        .setPageSize(3)
                                        .build();

                                FirestorePagingOptions<FoodItems> options = new FirestorePagingOptions.Builder<FoodItems>()
                                        .setQuery(query, config, FoodItems.class)
                                        .build();

                                food_items_recycle_adapter = new Food_Items_Recycle_Adapter(options, progressIndicator,null);
                                recyclerView.setHasFixedSize(true);
                                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                                recyclerView.setAdapter(food_items_recycle_adapter);
                                food_items_recycle_adapter.notifyDataSetChanged();
                                food_items_recycle_adapter.startListening();

                            }else {
                                Log.d(TAG, "onEvent: this is nulll");
                            }


                        }
                    }
                });
    }

谢谢你@s_o_m_m_y_e_e,你试图解决我的问题。 应该有很多方法可以归档它,但这是我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2011-08-18
    • 2022-07-11
    • 1970-01-01
    • 2019-09-17
    • 2022-08-20
    相关资源
    最近更新 更多