How can I check if a value e.g. name exists in a collection within any of documents in Cloud Firestore?

妖精的绣舞 提交于 2021-02-17 06:44:05

问题


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?


回答1:


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());
        }
    }
});

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.



来源:https://stackoverflow.com/questions/65936494/how-can-i-check-if-a-value-e-g-name-exists-in-a-collection-within-any-of-docume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!