Google firebase检查是否存在孩子 [英] Google firebase check if child exists

查看:91
本文介绍了Google firebase检查是否存在孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在android上创建一个应用程序。我需要检查我的数据库的一个给定的元素是否有一个给定的名字的孩子。我希望这可以通过使用以下几行来完成:

  DatabaseReference rootRef = FirebaseDatabase.getInstance()。getReference() ; 
$ b $ if(rootRef.childExists(name)){
//运行一些代码
}

我搜索了但我没有找到有用的东西。感谢您提前给予帮助。

值得一提:我认为值得一提的是,这实际上是下载所有数据在这个快照只是为了检查是否有数据存在。你应该在这里留意。如果引用是巨大的(例如实际根引用,而不是特定的子/属性),那么你应该找到一个更深的节点,你可以用来检查存在或设计不同的数据结构,检查是可能的。



数据库引用实际上是该数据的URL。您希望实际获取数据以查看是否存在小孩。这就是为什么您要查找的方法在 DataSnapshot

  DatabaseReference rootRef = FirebaseDatabase.getInstance()。getReference(); 
rootRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
void onDataChange(DataSnapshot snapshot){
if(snapshot.hasChild(name)){
//运行一些代码
}
}
});

现在,这个设计模式感觉有点奇怪。您正在阅读整个数据库,以查看是否存在名称。你可以通过监听 rootRef.child(name)来提高效率,然后检查是否存在 snapshot.exists() code $。

如果你想在这里做验证,而不是控制流,你应该考虑把这个代码放在你的 rules.json



编辑:我最初使用了错误的函数名childExists而不是hasChild)


I am trying to create an app on android. I need to check if a given element of my database on firebase has a child with a given name. I hoped it could be done by using something along the lines of:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

if (rootRef.childExists("name")) {
    //run some code
}

I searched but I didn't find anything useful. Thanks for any help in advance.

解决方案

Edit 2; worth putting on top: I think it is worth mentioning that this is actually downloading all data at this snapshot just to check whether any data exists. You should be mindful here. If the reference is huge (e.g. actually the root reference and not a specific child/property) then you should either find a deeper node you can use to check for existence or design your data structure differently so an efficient check is possible.

A database reference is effectively the URL for that data. You want to actually get data to see whether a child exists. This is why the method you seem to be looking for is on DataSnapshot.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  void onDataChange(DataSnapshot snapshot) {
    if (snapshot.hasChild("name")) {
      // run some code
    }
  }
});

Now, this design pattern feels a bit strange. You're reading the whole database just to see whether "name" exists. You can make this a bit more efficient by listening to rootRef.child("name") and then just checking whether snapshot.exists().

If you're trying to do validation here, and not control flow, you should consider putting this code in your rules.json.

edit: I originally used the wrong function name (childExists instead of hasChild)

这篇关于Google firebase检查是否存在孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆