Firestore文档参考数组 [英] Firestore Array of Document References

查看:48
本文介绍了Firestore文档参考数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Firestore数据库具有以下结构:

I have the following structure of my Firestore database:

products:{ // Collection
    procuct_1: { // Document
       title:"",
       url:""

videos:{ // Collection
    video_1:{ // Document
       title:"",
       products:{ // Array of references 
            0: "/products/product_1,
            1: "/products/product_2

我希望能够从视频收藏夹中的数组"字段获取对产品收藏夹的文档引用,以便获取此收藏夹中某些字段的值(例如产品标题).

I would like to be able from Array field in Videos Collection to get Document References to Products collection in order to get values of some fields of this collection (ex. title of product).

目前我使用此代码:

    FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseFirestore
            .collection("videos")
            .get()
            .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {
                        DocumentSnapshot documentSnapshot = task.getResult();

                        Map<String, Object> map = documentSnapshot.getData();
                        for (Map.Entry<String, Object> entry: map.entrySet()){
                            if (entry.getKey().equals("products")){
                               textView.setText(entry.getValue().toString());
                            }
                        }

但是entry.getValue().toString()向我返回了这样的数组:

But entry.getValue().toString(), returns me such array:

[com.google.firebase.firestore.DocumentReference@451d5ae8,

com.google.firebase.firestore.DocumentReference@e28cd0c]

关于如何从此数组中获取产品集合的任何字段的任何建议?

Any suggestions how I can get any field of Product collection from this Array?

推荐答案

要解决此问题,请使用以下代码:

To solve this, please use the following code:

firebaseFirestore.collection("videos")
    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            for (DocumentSnapshot document : task.getResult()) {
                List<String> products = (List<String>) document.get("products");
                for (String product : products) {
                    Log.d("TAG", product);
                }
            }
        }
    });

输出将是:

/products/product_1
/products/product_2

这篇关于Firestore文档参考数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆