如何在Firestore Array中添加对象



一般上下文:我有一个firestore列表,具有PastInventoryItem,每个都有一个名为countedquantity的数组。.

data class Material(
var type: String = "",
var material: String = "",
var size: String = "",
var description: String = "",
var unit: String = "",
var quantity: String = "0",
var actualquantity: String = "0") : FireStoreData()

下面是PastInventoryItem对象的Model类

data class PastInventoryItem(
var username: String = "",
var date: String = "",
var countedquantity: ArrayList<Material> = arrayListOf()) : FireStoreData()

当PastInventoryItem被存储时,如果我有文档ID,我想在Firestore中保存的countedquantity数组上添加一个Material。我所有的尝试最终都覆盖了原来保存的countedquantity,即使我使用setopoptions .merge()。

db.collection("Project").document(Prefs.getString("ManageID",
GlobalObject.FIRESTORE_ID))
.collection("pastInventories")
.document(documentID)
.set(pastInventoryItem, SetOptions.merge())
.addOnSuccessListener(unused -> {
Toast.makeText(materialDialog.getContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(e -> {
Toast.makeText(materialDialog.getContext(), "FAILURE", Toast.LENGTH_LONG).show();
});

当您调用set(..., SetOptions.merge())时,Firestore从第一个参数中获取所有值,并用它们替换数据库中的值。由于传递的是包含所有三个字段的PastInventoryItem,因此数据库中的所有三个字段都将被替换。


如果你想替换数据库中的单个字段,传递一个map使用单个字段,或者使用字段名和值,如更新文档的文档中所示。例如,只更新countedquantity字段:

Map updates = new HashMap();
updates.put("countedquantity", /* your value here */);
db.collection("Project").document(Prefs.getString("ManageID",
GlobalObject.FIRESTORE_ID))
.collection("pastInventories")
.document(documentID)
.set(updates, SetOptions.merge())

现在这段代码将只更新countedquantity字段,但它仍将取代整个领域。


如果您想项添加到countedquantity数组中,请使用文档中提到的array-union操作来更新数组中的项。例如,要将pastInventoryItem项添加到数组中:

Map updates = new HashMap();
updates.put("countedquantity", FieldValue.arrayUnion());
db.collection("Project").document(Prefs.getString("ManageID",
GlobalObject.FIRESTORE_ID))
.collection("pastInventories")
.document(documentID)
.set(updates, SetOptions.merge(pastInventoryItem))

注意项只会说如果没有相同的条目数组中。类似地:你可以用array-remove删除一个项目(如果你知道它的整个值)。


如果您想对数组进行任何其他类型的突变,您很可能必须分步骤执行操作:

  1. 从数据库中读取文档,并从数组字段中获取当前值。
  2. 在你的应用程序代码中更新数组。
  3. 将整个数组写回数据库。

鉴于您正在根据其当前值修改文档,您将希望为此使用事务。

最新更新