简体   繁体   English

Firebase 存在()与 null

[英]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.我不使用hasChild()因为我知道在大型数据集上这可能需要一些时间来查询。 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?但是,最近我遇到了在文档中找到的方法exists()现在我只是想知道这与我只是检查快照是否为空有什么不同? And how does the exists() function work? exists()函数是如何工作的? Like hasChild() iterates over the dataset what does esists() do?就像hasChild()遍历数据集一样, esists()做了什么?

And is it better than checking for null?它比检查 null 更好吗? the documentation doesn't say much文档没有说太多

thanks谢谢

UPDATE 1更新 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.现在我正在使用 hasChild() 我的理解,尽管这将遍历整个节点,直到找到它并返回它否则不会返回任何东西。 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.如果此 DataSnapshot 包含任何数据,则返回 true。 It is slightly more efficient than using snapshot.val() !== null.它比使用 snapshot.val() !== null 稍微高效一点。

Firebase exists documentation Firebase 存在文档

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.但总的来说,这种场景更适合交易,它将获取节点的当前值和设置其新值组合到一个操作中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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