2017-10-17 252 views
0

我使用火力地堡如下:火力地堡重置鍵

Post-- 

    -Kwc6asRRI1SUqrigYeD     <- First input 
         -> Date: 1:00pm 
         -> ID: 1 
         -> Content: Hello! 
    -Kwc6fXQsN2xIQtHOofZ 
         -> Date: 2:00pm 
         -> ID: 2 
         -> Content: How are you? 
    -Kwc6fXQsN2xRO39LDPD     <-Most recent one 
         -> Date: 3:00pm 
         -> ID: 3 
         -> Content: I am good. 

這些被「推送」,從而產生一個唯一的密鑰,其可用於根據"most recent to old"(或ID:3ID:1)顯示它們。

現在,當我需要更新數據,讓說ID:1文章內容從"Hello""My name is Steve",那麼它仍然保持着,即使這是最近的一個獨特的密鑰。

Post-- 

    -Kwc6asRRI1SUqrigYeD     <-Most recent one 
         -> Date: 4:00pm 
         -> ID: 1 
         -> Content: My name is Steve 
    -Kwc6fXQsN2xIQtHOofZ 
         -> Date: 2:00pm 
         -> ID: 2 
         -> Content: How are you? 
    -Kwc6fXQsN2xRO39LDPD     
         -> Date: 3:00pm 
         -> ID: 3 
         -> Content: I am good. 

我想我可以刪除帖子並設置一個新的帖子,但這似乎效率低下,特別是如果我有更多的數據在每個孩子。

有沒有辦法重新設置密鑰,以便它反映時間變化(如下所示)?

Post-- 

    -Kwc6fXQsN2xIQtHOofZ 
         -> Date: 2:00pm 
         -> ID: 2 
         -> Content: How are you? 
    -Kwc6fXQsN2xRO39LDPD     
         -> Date: 3:00pm 
         -> ID: 3 
         -> Content: I am good. 

    -Kwc6asRRI1KDodkeixk    <-Most recent one 
         -> Date: 4:00pm 
         -> ID: 1 
         -> Content: My name is Steve 

回答

2

沒有辦法更新現有節點的關鍵(見123)。如果你想要一個新的密鑰,你必須生成一個具有相同內容的新節點。

但在這種情況下,它似乎更可能是你要保持你的數據結構爲,而是增加一個lastUpdated時間戳到每個崗位:

Post-- 
    -Kwc6asRRI1SUqrigYeD 
        -> Date: 1:00pm 
        -> lastUpdated: 1508215054096 
        -> ID: 1 
        -> Content: Hello! 
    -Kwc6fXQsN2xIQtHOofZ 
        -> Date: 2:00pm 
        -> lastUpdated: 1507610306270 
        -> ID: 2 
        -> Content: How are you? 
    -Kwc6fXQsN2xRO39LDPD 
        -> Date: 3:00pm 
        -> lastUpdated: 1508128668412 
        -> ID: 3 
        -> Content: I am good. 

有了這個結構,你可以使用一個火力地堡查詢以您想要的順序獲得結果。在JavaScript中,這看起來像這樣:

var ref = firebase.database().reference("Post"); 
ref.orderByChild("lastUpdated") 
    .once("value") 
    .then(function(snapshot) { 
    snapshot.forEach(function(post) { 
     console.log(snapshot.key+": "+snapshot.val().Content); 
    }); 
    }); 
+0

謝謝弗蘭克!非常感激。 –