如何使用哈希映射在firebase firestore android中添加/更新/删除数组元素?存储数据库

我想做一个用户的集合,用户将有多个存储作为文档,每个文档都有像,和.我的问题是,如何管理可用的产品阵列?我知道Firestore不能处理数组,我应该使用HashMap。我的可用产品可能有产品名称,产品价格等字段。我是 Firebase 的新手,如何在 Android Studio 中使用 java 管理数组?storeNamestoreAddressavailableProductsavailableProduct

FireBase Firestore DataBase Image


答案 1

好消息是,随着数组的最新改进,您可以添加,更新和删除数组元素。

查看此博客文章:云 Firestore 中更好的阵列!

你可以这样做

//Map to add user to array
final Map<String, Object> addUserToArrayMap = new HashMap<>();
addUserToArrayMap.put("arrayOfUsers", FieldValue.arrayUnion(mAuth.getCurrentUser().getUid()));

//Map to remove user from array
final Map<String, Object> removeUserFromArrayMap = new HashMap<>();
removeUserFromArrayMap.put("arrayOfUsers", FieldValue.arrayRemove(mAuth.getCurrentUser().getUid()));

//use either maps to add or remove user
db.collection("REFERENCE").document("mDocumentId")
                .update(addUserToArrayMap);

答案 2

编辑:2018年9月12日

从 开始,现在可以更新数组成员。更多信息请点击这里August 28, 2018


如何在火库火库中添加/更新/删除数组元素?

简短的回答是你不能!如有关数组的官方文档所示:

虽然 Cloud Firestore 可以存储数组,但它不支持查询数组成员或更新单个数组元素。

因此,目前无法在 Cloud Firestore 数据库中添加、更新或删除单个数组元素。

看到你的数据库模式,我可以说你没有任何数组。是一个对象,在其下方有一个名为的映射,其中包含两个 String 属性和 。如果您想更新,请说价格,请使用以下代码:availableProducts0spNamespPrice

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference ref = rootRef.collection("gdgsghs.cok").document("Shsheg");
Map<String, Object> availableProducts = new HashMap<>();
Map<String, Object> zeroMap = new HashMap<>();
Map<String, Object> product = new HashMap<>();
product.put("spPrice", 63.121);
zeroMap.put("0", product);
availableProducts.put("availableProducts", zeroMap);
ref.set(availableProducts, SetOptions.merge());

您的价格将从 更新为 。67.36863.121


推荐