java - Firestore 更新 2 个不同的文档
问题描述
我在我的应用程序中使用 Cloud Firestore,并且有 2 个集合Customers
和Properties
. 我有一个活动,用户可以更新包含在客户文档名称地址等中的数据。下面显示的代码工作正常。
db.collection("Customers").document(customer.getCustomerId())
.update(
"name", c.getName(),
"email", c.getEmail(),
"phoneNo", c.getPhoneNo(),
"address", c.getAddress(),
"creatorId", c.getCreatorId()
)
.addOnCompleteListener(new OnCompleteListener<Void>() {
我在属性文档中保存了客户的文档参考,因此我可以参考哪个客户拥有哪个属性。使用此参考,我想搜索包含该参考的属性,并在名称字段已更改时更新它。在 onComplete 检查上述代码之后,我尝试将代码添加到我的方法中,但它不会每次仅每隔几次尝试就更新名称字段。
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference propRef = rootRef.collection("Properties");
propRef.whereEqualTo("customerId", customerId).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
Map<Object, String> map = new HashMap<>();
map.put("customer", customerName);
propRef.document(document.getId()).set(map, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
有没有办法实现我想要做的事情?我确实认为我可以使用批处理来完成,但从我读过的内容来看,这不允许搜索。
@AlexMamo
这是我的客户收藏中的一份文件
这是我的 Properties 集合中的链接文档
客户结构
属性结构
解决方案
根据您的意见,要解决您的问题,请使用以下代码行:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference propertiesRef = rootRef.collection("Properties");
CollectionReference customersRef = rootRef.collection("Customers");
customersRef.whereEqualTo("customerId", customerId).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String customerName = document.getString("name");
propertiesRef.whereEqualTo("customerId", customerId).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot doc : task.getResult()) {
propertiesRef.document(doc.getId()).update("customer", customerName);
}
}
}
});
}
}
}
});
看到您应该使用不同的CollectionReference
对象,propertiesRef
并且customersRef
您使用的是单个对象。
推荐阅读
- python - 使用 API 提取 5 年的 Twitter 数据
- node.js - Azure 应用服务上 Angular 应用的服务器端渲染导致 SNAT 端口耗尽
- lua - GLua 的问题:“GetModel() 不是字符串库的一部分”
- c - 非全局使用的 getopt (C) 中的错误?
- kubernetes - 如何在 k8s 中为非服务帐户创建不记名令牌
- android - 使用 Retrofit2 和 Flow 同时进行多个 API 调用
- php - 条件为假时多维数组中的array_slice
- linux - 检查条件并在 bash 中运行命令
- c# - 如何在 .NET Core 中模拟 HttpContext.GetServerVariable()
- javascript - 如何在 highcharts.js 中放置标签工具提示