【问题标题】:Firebase limitToFirst doesn't work as expectedFirebase limitToFirst 无法按预期工作
【发布时间】:2015-01-10 19:24:46
【问题描述】:

我正在使用 Firebase 检索用户的一些数据。我需要使用“gameSearching: true”检索只有一个用户。

我现在得到了以下代码:

var ref = new Firebase("https://grootproject.firebaseio.com/Users");
    ref.orderByChild("gameSearching").equalTo(true).limitToFirst(1).on("child_added", function (data) {
        var yourself = firebase.getAuth().password.email.split("@", 1)[0];
        var opponent = data.key();

        setData(('Users/' + opponent + '/'), {gameSearching: false});
        setData(('Users/' + yourself + '/'), {gameSearching: false});

        console.log(opponent);
    });

当我运行此代码时,该函数将运行两次。 我正在使用limitToFirst(1),所以我希望只检索一个用户。

我做错了什么?

【问题讨论】:

  • 如果您希望处理程序只执行一次,请使用.once('child_added'。如果您不这样做,它就会变成一个过滤后的 view,并且该视图中的数据可能会随着时间的推移而更新。发生这种情况时,Firebase 还会触发 child_removed 事件,因此任何时候都只有一个孩子在视图中。

标签: javascript json firebase


【解决方案1】:

参考文献

当您使用 on('child_added' 将侦听器添加到 Firebase 时,将为创建的每个子级调用它。

ref.on('child_added', function(s) { console.log(s.key()); });

所有初始子项和都将触发此函数,以后添加的任何子项都会触发。

在您的 Firebase 中,这是数据:

hallo: gameSearching=false
sam_lous: gameSearching=true
test: gameSearching=false
test2: gameSearching=true

查询

当您向查询添加侦听器时,将为属于查询的每个子级调用它:

ref.orderByChild("gameSearching").equalTo(true).on("child_added‌​", function (s) { console.log(s.key()); })

因此,这将记录所有立即和搜索游戏的用户以及稍后开始搜索游戏的用户。

sam_lous: gameSearching=true
test2: gameSearching=true

因此,当您对之前未搜索游戏的用户调用 user.update({ gameSearching: true }) 时,将触发该函数。您实际上看到的是所有正在搜索游戏的用户的列表,而 Firebase 会为您更新该列表。

假设用户test 开始搜索游戏。当他的gameSeaching 设置为true 时,您将收到child_added 事件:

test: gameSearching=true

同样,当用户测试停止搜索游戏时(通过调用 user.update({ gameSearching: false })),Firebase 将通过 child_removed 事件通知您。

有限的查询

我们仍然有 3 个用户在搜索游戏:

sam_lous: gameSearching=true
test: gameSearching=true
test2: gameSearching=true

您将侦听器添加到对其有限制的查询:

ref.orderByChild("gameSearching").equalTo(true).limitToFirst(1).on("child_added‌​", function (s) { console.log(s.key()); })

这将触发一个 child_added 事件:

sam_lous: gameSearching=true

现在您的代码将 sam_lous 与对手匹配,并将 sam_lous 的 gameSearching 值设置为 false。所以 sam_lous 不再属于查询。 Firebase 仍会使查询保持最新状态,因此它会:

  1. 为 sam_lous 发送 child_removed 事件
  2. 为test(下一个正在搜索游戏的玩家)发送child_added 事件

使用 Firebase 时要始终牢记的是,您不是在查询数据库,而是在同步数据。既然您要求 Firebase 提供正在搜索游戏的单个玩家的同步列表,那么它就是这样做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2014-12-09
    • 2016-01-13
    • 2020-09-21
    • 2011-08-17
    • 2012-04-29
    • 2021-08-12
    相关资源
    最近更新 更多