firestore — Add element in a field in hashmap

一世执手 提交于 2020-01-23 20:30:08

问题


Above is the structure of collection "networks". What is want to do is add another element in "users" field. It's a HashMap. I want to achieve is Key= xyz@gmail.com and its values {displayName: "Anirudh Kumar", "role":"admin"}.

xyz@gmail.com displayName: "Anirudh Kumar" role: "admin"

I have tried few things but it doesn't seems to work.

1st option

        Map<String, Network.NetworkUser> users = new HashMap<>();
        users.put(email, networkUser);

       db.collection("networks").document("id")
          .update("users",FieldValue.arrayUnion(users));

2nd option

       db.collection("networks").document(userNetwork.getNetworkUid())
                                .set(users,SetOptions.merge());

3rd option

                            db.collection("networks").document(userNetwork.getNetworkUid())
                                .update("users."+email,networkUser);

3rd option takes me closer to answer, but because of dot [.] in an email it creates another row, let me know if somehow this can be avoided.

If anyone can assist me how can I achieve the desired goal, it would be appreciated. Thanks.


回答1:


None of your attempts work because you are trying to update a document using a Map in which the value is an object of type Network.NetworkUser and this is not possible, because there is no way you can map that object to a HashMap.

What is users property? In fact, is a property of type Map, which contains in terms other HashMaps. So you need to get the document first, get the value of users property, cast to a Map<String, Object> and put inside another HashMap. This new HashMap contains an object with the email address as the key and another HashMap as a value, which again in terms contains two keys with two values. After you add the desired data to the Map, simply write the document back.

If you don't want that behavior, you can simply create a subcollection of users under each (Network.NetworkUser) document.



来源:https://stackoverflow.com/questions/59611061/firestore-add-element-in-a-field-in-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!