英文:
How to remove item in list with WriteBatch?
问题
fireDB.document(groupPath).collection("users").whereArrayContains("cars", carPath).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
QuerySnapshot snapshot = task.getResult();
WriteBatch batch = fireDB.batch(); // Initialize WriteBatch
for (DocumentSnapshot curr : snapshot.getDocuments()) {
List<String> cars = (List<String>) curr.get("cars");
if (cars == null) continue;
if (cars.size() <= 2) {
batch.delete(snapshot.getReference());
} else {
cars.remove(carPath); // Remove the string from the list
batch.update(curr.getReference(), "cars", cars); // Update the document with modified list
}
}
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> batchTask) {
if (batchTask.isSuccessful()) {
// Batch write successful
} else {
// Batch write failed
}
}
});
}
}
});
英文:
I'm using Firebase Cloud database. I queried a collection and got a list of documents. Each document contains a field cars
which contains strings. In case the array contains at least three strings I want to remove the string carPath
from this array (not the whole array). Otherwise, it should remove the whole document. I'm using WriteBatch. What I did:
fireDB.document(groupPath).collection("users").whereArrayContains("cars",carPath).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
QuerySnapshot snapshot = task.getResult();
for (DocumentSnapshot curr : snapshot.getDocuments()) {
List<String> cars = (List<String>) curr.get("cars");
if (cars == null) continue;
if (cars.size() <= 2) {
batch.delete(snapshot.getReference());
} else {
// What to do here?
}
}
}
}
});
How should I remove one item in the list with WriteBatch?
答案1
得分: 1
你所尝试做的只是一个文档更新。你可以使用FieldValue.arrayRemove()进行常规更新。唯一不同的是,你会在批处理的上下文中使用update(),而不是独立的更新。
batch.update(snapshot.getReference(), "cars", FieldValue.arrayRemove(carPath));
英文:
What you're trying to do is just a document update. You can do a regular update with FieldValue.arrayRemove(). Except you will do it in the context of a batch using update() instead of a standalone update.
batch.update(snapshot.getReference(), "cars", FieldValue.arrayRemove(carPath));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论