2017-01-02 79 views
0

我試圖將兩個相關項目添加到我的Firebase數據庫。我想推送一個項目,然後獲取該項目的新創建的密鑰,並將其用作另一棵樹中第二個項目的密鑰。我試過查詢數據庫以獲取創建的最後一個密鑰並將其用作第二次推送的密鑰,但它仍然只是爲其生成一個新密鑰。這裏是我使用的代碼:使用Firebase按鍵作爲第二個按鍵的關鍵

save: function() { 
    if (this.$.document.isNew && (this.editableCard.title || this.editableCard.body)) { 
     return this.$.document.save(this.cardsPath).then(function() { 
      this.$.document.reset(); 
      var sceneRef = firebase.database().ref().child(this.cardsPath); 
      var scene = sceneRef.orderByKey().limitToLast(1); 
      var sceneKey = scene.key; 
      this.$.document.save('/documents/', sceneKey); 
     }.bind(this)); 
    } 
    return Promise.resolve(); 
} 

(我使用Polymer,我的出發點是Polymerfire的note-app演示)。

關於如何檢索第一次推送的新密鑰並將其用於第二次推送的任何想法?謝謝!

編輯

我發現火力地堡的文檔閱讀的答案,並寫入數據庫的Web。 Link

回答

1

push()立即返回DatabaseReference。您可以使用getKey()來詢問引用它的關鍵是什麼,然後使用該字符串更新數據庫中的另一個位置。

0

您可以在原始數據庫參考訪問關鍵性能和使用,作爲第二個關鍵,像這樣:

let firstObjRef = firebase.database().ref('/first/path/).push(firstObj, (error) => { 
    videoObj["roomUploadedTo"] = this.roomName; 
    var updateObj = {}; 
    updateObj[videoObjRef.key] = videoObj; 

    firebase.database().ref('/second/path/').update(updateObj).then((e) => { 
    console.log('update went through. booyah! ' + e); 
    })