简体   繁体   中英

Firebase exists() vs null

Normally when I check to see if the database contains a node I do something like:

users = dbReference.getReference("users").child(someUser);

I do not use hasChild() because I know on a large dataset this can take sometime to query. However, recently I ran into the method exists() found here on documentation now I was just wondering how does this differ from me just checking if the snapshot is null? And how does the exists() function work? Like hasChild() iterates over the dataset what does esists() do?

And is it better than checking for null? the documentation doesn't say much

thanks

UPDATE 1

Assuming i have the following node:

示例节点

When a user wants to register, I check this node to see if the username is taken:

userTakenNode.addListenerForSingleValueEvent(new ValueEventListener() {


        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (!dataSnapshot.hasChild(enteredUsername)) {
                register();
            } 

        }

If the username is not taken then I register the user with that username and add the username to the node above. Now I am using hasChild() to my understanding though this will iterate over the whole node till it finds it and will return it else wont return anything. On a large dataset this can take very long.

Is there a quicker way to query the dataset?

exists is slightly more efficient:

Returns true if this DataSnapshot contains any data. It is slightly more efficient than using snapshot.val() !== null.

Firebase exists documentation

You'll definitely want to only check the specific user name. So attach your listener one level lower in the tree:

userTakenNode.child(enteredUsername).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (!dataSnapshot.exists) {
            register();
        } 
    }

But in general this scenario is better suited for a transaction , which combines getting the current value of the node and setting its new value into a single operation.

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