一般上下文:我有一个具有PastInventoryItems,的火药库列表,每个列表都有一个名为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对象的模型类
data class PastInventoryItem(
var username: String = "",
var date: String = "",
var countedquantity: ArrayList<Material> = arrayListOf()) : FireStoreData()
当存储PastInventoryItem时,只要我有文档ID,我想在Firestore中保存的countedquantity数组上添加一个材料。即使在使用SetOptions.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();
});
发布于 2022-07-11 06:04:08
当您调用set(..., SetOptions.merge())
时,Firestore从第一个参数中获取所有值,并用它们替换数据库中的值。因为您传递的是一个包含所有三个字段的PastInventoryItem
,所以数据库中的所有三个字段都会被替换。
如果要替换数据库中的单个字段,请使用单个字段传递一个映射,或者传递一个字段名和一个值,如更新文档文档中所示。例如,要只更新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
删除一个项(如果您知道它的整个值)。
如果希望对数组进行任何其他类型的突变,则很可能必须分步骤执行该操作:
考虑到您正在根据文档的当前值修改文档,您需要对此进行使用事务。
https://stackoverflow.com/questions/72937866
复制