简体   繁体   中英

Firebase: Checking whether a value already exists in any of the child nodes or not

I want to find whether a email (entered by the user) already exists in the my Firebase child node or not.

How do i check it?

MY PROGRAM:

String email = "emailEnteredByUser@gmail.com";
Query check = FirebaseDatabase.getInstance().getReference("student").child(RANDOM_ID).orderByChild("email").equalTo(email);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            if(snapshot.exists())
            {
                Toast.makeText(this, "Email already exists!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "Email doesn't exists!", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    };
    check.addListenerForSingleValueEvent(eventListener);

note: i'm using RANDOM_ID just for the reference, it'll be randomly generated id's

这是我的 Firebase 数据库

When you run a query on that path, Firebase checks the condition for each child directly under that path. Since you run the query on /student/$RANDOM_ID , it then checks each child node under that (so email , id , etc) whether they have a property email with the given value. And since there is no /student/$RANDOM_ID/email/email , the query doesn't match any nodes.

The correct query to check whether any direct child node of student has a email property with the given value, is:

Query check = FirebaseDatabase.getInstance().getReference("student").orderByChild("email").equalTo(email);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM