2017-06-01 211 views
1

我在我的數據庫中的隊列,看起來像這樣:如何獲得瞬間的孩子不知道在火力和火力管理員的關鍵

server 
    queue 
    -RANDOM_ID_1234 
     active: "true" 
     text: "Some text" 
    -RANDOM_ID_5678 
     active: "false" 
     text: "Another text" 
    -RANDOM_ID_91011 
     active: "false" 
     text: "Text that does not matter" 

我要查詢和獲取活動項目:

queueRef.orderByChild('active').equalTo('true').once('value', function(snap) { 
    if (snap.exists()) { 
    console.log(snap.val()); 
    } 
}); 

console.log將返回類似:

{ 
    -RANDOM_ID_1234: { 
     active: "true" 
     text: "Some text" 
    } 
} 

如何獲取文本不知道關鍵?

我使用lodash(請參閱下面的答案),但必須有更好的方法來做到這一點。

回答

1

當你執行一個查詢對火力地堡數據庫中,有可能會有多個結果。所以快照包含了這些結果的列表。即使只有一個結果,快照也會包含一個結果列表。

一個火力地堡快照有一個內置的方式來遍歷其子:如果有像`getChildAtIndex(0)`或數組符號`[0]`

queueRef.orderByChild('active').equalTo('true').once('value', function(snapshot) { 
    snapshot.forEach(function(child) { 
    console.log(child.key+": "+child.val()); 
    } 
}); 
+0

將是真棒。 – Pier

0

我用lodash,並得到這樣的關鍵:

/* 
* I get the keys of the object as array 
* and take the first one. 
*/ 
const key = _.first(_.keys(snap.val())); 

,然後得到從卡文是這樣的:

/* 
* then I create a path to the value I want 
* using the key. 
*/ 
const text= snap.child(`${key}/text`).val();