You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase Web数据库中获取在线用户的指定字段数据?

完善Firebase getUsers函数实现

现有数据库结构与在线状态设置代码

你的Firebase数据库结构如下:

users:
  000:
    game:
      cord_x: 0
      cord_y: 0
      online: true
    password: "000"

设置用户在线状态的代码:

get(ref(db, `users/${db_uname}/game`)).then((snapshot) => {
  if (!(snapshot.exists())) {
    set(ref(db, `users/${db_uname}/game`), {
      cord_x: 0,
      cord_y: 0,
      online: true
    });
  }
  update(ref(db, `users/${db_uname}/game`), {
    online: true
  });
  var con = true;
  window.db_con = con;
});

需求说明

需要实现getUsers函数,从所有game/online字段为true的用户中,提取用户名(用户节点的key)、game/cord_x、game/cord_y字段,然后调用create_hero(name, x, y)函数。

完善后的getUsers函数

function getUsers() {
  get(child(db, `users/`)).then((snapshot) => {
    // 遍历所有用户节点
    snapshot.forEach((userSnapshot) => {
      // 获取用户名(即用户节点的标识)
      const username = userSnapshot.key;
      // 提取用户的游戏数据
      const gameData = userSnapshot.child('game').val();
      
      // 过滤出在线状态为true的用户
      if (gameData?.online === true) {
        const x = gameData.cord_x;
        const y = gameData.cord_y;
        // 调用创建英雄的函数
        create_hero(username, x, y);
      }
    });
  }).catch((error) => {
    // 捕获并处理请求异常
    console.error('获取用户数据失败:', error);
  });
}

代码说明

  • 用snapshot.forEach遍历所有用户节点,每个userSnapshot对应单个用户的完整数据
  • 通过userSnapshot.key直接获取用户名(即数据库中用户节点的唯一标识,比如示例中的"000")
  • 用userSnapshot.child('game').val()提取用户的游戏相关字段
  • 可选链操作符?.避免因game节点不存在引发的报错,同时精准筛选在线用户
  • 新增错误捕获逻辑,避免请求失败导致程序异常

内容的提问来源于stack exchange,提问作者Mapagmataas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 05:10:42