Firebase queryOrderedbyChild不返回Null值 [英] Firebase queryOrderedbyChild doesn't return a Null value

查看:65
本文介绍了Firebase queryOrderedbyChild不返回Null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,可以根据用户的年龄进行搜索:

I have a query that searches for users based on their age:

self?.ref.child("users").queryOrdered(byChild: "age").queryStarting(atValue: "18").queryEnding(atValue: "25").observeSingleEvent(of: .childAdded, with:  { (snapshot) in
    print(snapshot)

我的Firebase结构如下:

My Firebase structure is like this:

users
    -> uid1
        -> age : "18"
        -> name : "Lisa"
        -> ...
    -> uid2
        -> age : "18"
        -> name : "Elizabeth"
        -> ...

在我的数据库中,有两个年龄在18岁的人.

In my DB there are two people withe age : "18".

当queryStartingAtValue为"18"时,一切正常.

Everything works well when queryStartingAtValue is "18".

当我将queryStartingAtValue更改为不存在的年龄(例如"19")时,就会发生此问题.

The issue occurs when I change the queryStartingAtValue to the non-existing age (e.g. "19").

确实,没有返回结果,数据似乎在查询中被阻止.

Indeed, no results are returned, the data seems to be blocked inside the query.

您是否知道此查询出了什么问题?

Do you have any idea what's wrong with this query?

谢谢.

推荐答案

在显示的数据中,没有节点的19或更高,因此查询不匹配任何节点.在这种情况下,.childAdded事件不会触发.

In the data you show there are no nodes with 19 or higher, so the query doesn't match any nodes. In that case the .childAdded event does not fire.

如果要检测到这种情况,则必须收听.value事件,即使没有孩子,该事件也会触发 .但是在这种情况下,您将为所有匹配的子项获得一个.value事件,因此您需要

If you want to detect this condition, you must listen to the .value event, which does fire even when there are no children. But you'll get a single .value event for all matching children in this case, so you'll need to loop over the child nodes:

self?.ref.child("users")
  .queryOrdered(byChild: "age").queryStarting(atValue: "18")
  .queryEnding(atValue: "25")
  .observeSingleEvent(of: .value, with:  { (snapshot) in
    print(snapshot.exists())
    for child in snapshot.children {
      ...
    }

这篇关于Firebase queryOrderedbyChild不返回Null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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