Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

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

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...