如何检查一个值,例如名称是否存在于Cloud Firestore中任何文档的集合中? [英] How can I check if a value e.g. name exists in a collection within any of documents in Cloud Firestore?
问题描述
我想检查是否有一个值,例如(名称:"John")存在于我的Cloud Firestore中任何文档的集合中,因为如果这样的话,我不想创建具有该名称的新文档(在本例中为"John").如何检查名称是否存在?
I want to check if a value e.g. (name: ‘John’) exists in the collection of any document in my Cloud Firestore, because if it does I do not want to create a new document with that name (in this case ‘John’). How can I check if the name exists?
推荐答案
假定您在Firestore中有一个名为"users"的集合,以检查是否有名称为"John"的用户.已经存在,请使用以下代码行:
Assuming you have in Firestore a collection called "users", to check if a user with the name of "John" already exists, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
Query queryUsersByName = usersRef.whereEqualTo("name", "John");
queryUsersByName.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.exists()) {
Log.d("TAG", "name already exists");
} else {
//Do what you need to do
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});
如果名称为"John"的用户被拒绝,则上述代码的结果将是带有消息名称已存在"的日志语句.已经存在于用户"列表中.集合.
The result of the above code will be a log statement with the message "name already exists", if a user with the name of "John" already exists in the "users" collection.
这篇关于如何检查一个值,例如名称是否存在于Cloud Firestore中任何文档的集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!