问题
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