【问题标题】:Cloud Firestore UpdateCloud Firestore 更新
【发布时间】:2018-09-24 13:31:07
【问题描述】:
我想根据文档中的值更新 Cloud Firestore 中的文档。像这样的东西。我很少有带有随机名称和值的文档,还有一个带有值 id = 1 , name = patryk 的文档。现在我要用name=patryk 更新文档。而且我不知道文档名称,因为我让它们像这样并且它们有一个随机名称。
b.collection("Users")
.add(postMapa)
.addOnCompleteListener
如何做到这一点? here我需要文档的名称,但我没有。
【问题讨论】:
标签:
android
firebase
google-cloud-firestore
【解决方案1】:
试试这个,确保 name = patryk 只有一个文档
db.collection("Users").whereEqualTo("name", "patryk").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (e == null) {
String documentId = queryDocumentSnapshots.getDocuments().get(0).getId();
// here you have id but make sure you have only one document for name=patryk
}
}
});
【解决方案2】:
假设id 属性为数字类型,name 属性为字符串类型,请使用以下代码更新所有用户为id = 1 和name = patryk:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("Users").whereEqualTo("id", 1).whereEqualTo("name", "patryk");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
for (String id : list) {
rootRef.collection("Users").document(id).update("name", "New Name").addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Name Updated!");
}
});
}
}
}
});
如果您正在为您的用户使用模型类,请查看我在此 post 中的回答。
【解决方案3】:
您可以按名称检索文档(此处并不适用):
DocumentReference docRef = db.collection("Users").document("patryk");
或者您可以查询文档中包含的值(这可能会回答您的问题):
/* create a reference to the Users collection */
CollectionReference users = db.collection("Users");
/* create a query against the collection */
Query query = users.whereEqualTo("name", "patryk");
在这两种情况下,其余的过程都是相同的:
/* asynchronously retrieve the document */
ApiFuture<DocumentSnapshot> future = docRef.get();
/* future.get() blocks on response */
DocumentSnapshot document = future.get();
if (document.exists()) {
System.out.println("Document data: " + document.getData());
} else {
System.out.println("No such document!");
}
【解决方案4】:
获取集合下所有document id 的简单方法:
firebase.collection("Users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
Log.d(TAG, list.toString());
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});