firestore-在哈希图中的字段中添加元素 [英] firestore -- Add element in a field in hashmap
问题描述
以上是集合网络"的结构.要做的是在用户"字段中添加另一个元素.这是一个 HashMap
.我要实现的是Key = xyz@gmail.com及其值{displayName:"Anirudh Kumar","role":"admin"}.
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.comdisplayName:"Anirudh Kumar"角色:管理员"
xyz@gmail.com displayName: "Anirudh Kumar" role: "admin"
我尝试了几件事,但是似乎没有用.
I have tried few things but it doesn't seems to work.
第一个选项
Map<String, Network.NetworkUser> users = new HashMap<>();
users.put(email, networkUser);
db.collection("networks").document("id")
.update("users",FieldValue.arrayUnion(users));
第二个选项
db.collection("networks").document(userNetwork.getNetworkUid())
.set(users,SetOptions.merge());
第三个选项
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.
推荐答案
您的尝试均无济于事,因为您正尝试使用 Map
来更新文档,其中该值是类型为<的对象code> Network.NetworkUser ,这是不可能的,因为无法将对象映射到 HashMap
.
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
.
什么是 users
属性?实际上,它是 Map
类型的属性,其中包含其他HashMaps.因此,您需要首先获取文档,获取 users
属性的值,转换为 Map< String,Object>
,然后放入另一个 HashMap
.这个新的HashMap包含一个以电子邮件地址为键的对象,另一个 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.
如果您不希望出现这种情况,则只需在每个(Network.NetworkUser)文档下创建一个用户子集合.
If you don't want that behavior, you can simply create a subcollection of users under each (Network.NetworkUser) document.
这篇关于firestore-在哈希图中的字段中添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!