首页 > 解决方案 > 如何将 firebase 中特定 ref 的所有子对象放入一个对象中?

问题描述

这是我的 Firebase 结构。

在此处输入图像描述

我想像这样把它全部拿回来。

 {
"users": {
    "EFo7BemCuWVFyGYwk0CiTHR5fDB2": {
        "profile": {
            "-LMUD--2APhiSLkEtVbM": {
                "profileName": "bob",
                "profilePic": "https://scontent-iad3-1.xx.fbcdn.net/v/t1.0-1/c27.0.160.160/p160x160/205110_1018814483408_6876_n.jpg?_nc_cat=0&oh=2e40387a728c2f8c8d04b3299601be7e&oe=5C18FC6D",
                "score": 73,
                "teamName": "lzs"
            }
        },
        "team": {
            "-LPpWX5o8kmfCKUZBoYy": {
                "competitorKey": "-LNb6AEdyBSmeooeDhT0"
            },
            "-LPpWX_SMWHWsKauutVC": {
                "competitorKey": "-LNb42VDA4ZjW2EeVLLd"
            }
        }
    },
    "FIXBObMxXoOzFE7hsb4wHl8esfe2": {
        "profile": {
            "-LPqBizyqR-jEAsawYO7": {
                "profileName": "steve",
                "profilePic": "http://www.cricearena.com/images/rough_riders_new_medium_logo-u2182.png",
                "score": 43,
                "teamName": "twitterRangers4"
            }
        },
        "team": {
            "-LPqX9ncuK09WvnT3SIk": {
                "competitorKey": "-LNb6AEdyBSmeooeDhT0"
            }
        }
    }
  }
 }

我得到的只是用户中的密钥。

我的 redux 动作是

export function loadLeague() {
 return dispatch => {
leagueFireDB.path = `users/`;
leagueFireDB.subscribe(dispatch);
 };
}

我的高级 fb db 功能。

    subscribe(emit) {
let ref = firebaseDb.ref(this._path);
let initialized = false;
let list = [];

ref.once('value', () => {
  initialized = true;
  console.log("ONCE::",this._actions)
  emit(this._actions.onLoad(list));
});

ref.on('child_added', snapshot => {
  if (initialized) {
    emit(this._actions.onAdd(this.unwrapSnapshot(snapshot)));
  }
  else {
    list.push(this.unwrapSnapshot(snapshot));
  }
});

ref.on('child_changed', snapshot => {
  emit(this._actions.onChange(this.unwrapSnapshot(snapshot)));
});

ref.on('child_removed', snapshot => {
  console.log("REMOVE2::",snapshot)
  emit(this._actions.onRemove(this.unwrapSnapshot(snapshot)));
});

this._unsubscribe = () => ref.off();
}

所以很明显它会命中数据库中的“用户”节点,在那里抓取那些键。它不会遍历并返回所有属于 ref 的孩子(或者我猜是大孩子等)。我希望在数据库中获取 Users ref 的所有孩子,但我一直在环顾四周,没有发现任何可以做到这一点的东西。我对 redux firebase 做出反应。而已。没有 API/中间件。

标签: javascriptreactjsfirebasefirebase-realtime-databaseredux

解决方案


所以这给了我完整的对象,包括我正在寻找的所有孩子和孙子。

 subscribeChild(emit) {
   let ref = firebaseDb.ref(this._path);
   ref.once('value', snapshot => {
   emit(this._actions.onLoad(this.unwrapSnapshot(snapshot)));
   });
 }

这是我有的展开。

 unwrapSnapshot(snapshot) {
   let attrs = snapshot.val();
   attrs.key = snapshot.key;
   return new this._modelClass(attrs);
 }

我的加载操作请求正在调用 ref.once 高级 firebase db 调用,但我没有在那里解开快照。因此,我为这个加载请求创建了另一个名为 subscribeChild 的订阅发射器,并将 unwrapSnapShot 放入它返回的发射器中。果然,整个对象包含了所有子引用和键值数据。现在我必须弄清楚如何处理数据对象。:)

我只是通过这个 firebase RTDB 轻推我的方式,所以如果有人有意见或者我真的做错了,请发表评论,我会相应地更新或接受更好的答案。


推荐阅读