我正在使用 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)
,因此我希望只检索一个用户。
我做错了什么?
最佳答案
引用文献
当您使用 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
同样,当用户 test 停止搜索游戏(通过调用 user.update({ gameSearching: false })
)时,Firebase 会通过 child_removed
通知您> 事件。
有限查询
我们仍然有三个用户在搜索游戏:
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 仍会保持查询最新,因此它会:
- 为 sam_lous 发送
child_removed
事件 - 发送
child_added
事件以进行test
(下一个正在搜索游戏的玩家)
使用 Firebase 时要始终牢记的一点是,您不是在查询数据库,而是在同步数据。由于您要求 Firebase 提供正在搜索游戏的单个玩家的同步列表,这正是它的作用。
关于javascript - Firebase limitToFirst 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27880275/