2012-10-02 125 views
9

如果我這樣做,一切都很好用我的itemref:的itemref的我可以防止Firebase set()覆蓋現有數據嗎?

itemRef.child('appreciates').set(newFlag); 
itemRef.child('id').set(newId); 

其他屬性保持,但如果我這樣做child_changed被調用兩次

itemRef.set({appreciates:newFlag,id:newId}); 

child_changed被稱爲只有一次,但我的其他物業被摧毀。 除了重新填充整個參考對象的笨拙之外,還有一種解決方法嗎?

感謝,

+0

我們有一些未公開的新功能來解決這個問題。你能給我發電子郵件給安德魯在firebase點com嗎? –

+1

我認爲這現在已覆蓋「更新」 https://www.firebase.com/docs/javascript-client/firebase/update.html – vonmangle

回答

13

的火力地堡update()函數將允許您同時保留其他不變修改一個對象的一些孩子。無論有多少孩子被更改,更新功能只會觸發其他客戶端上的一個「值」事件,用於寫入的路徑。

在這個例子中,你可以這樣做:

itemRef.update({appreciates:newFlag,id:newId}); 

的文檔update() is here

+15

是否可以只寫入新數據,而不是覆蓋現有的? – Qwerty

0

我一直在努力做到這一點具有如下所示的結構:

Firebase gigs database structure

運行時,是我在這個問題上說的具體領域,如名稱,描述和日期,所有的設置

return (dispatch) => { 
    firebase.database().ref(`/gigs/${uid}`) 
     .set({ name, description, date }) 
     .then(() => { 
      dispatch({ type: GIG_SAVE_SUCCESS }); 
      Actions.home({ type: 'reset' }); 
     }); 
}; 

只留下了名稱,描述和日期節點,但使用以下的特定節點更新而不刪除其他子節點:其他子節點然後將用下面的刪除即成員,圖像等:

return (dispatch) => { 
    var ref = firebase.database().ref(`/gigs/${uid}`); 
    ref.child('name').set(name) 
    ref.child('description').set(description) 
    ref.child('date').set(date) 
     .then(() => { 
      dispatch({ type: GIG_SAVE_SUCCESS }); 
      Actions.home({ type: 'reset' }); 
     }); 
}; 
0

如果數據已經存在,您可以創建一個防止覆蓋的規則。 這裏轉載自Firebase docs Existing Data vs New Data

// we can write as long as old data or new data does not exist 
// in other words, if this is a delete or a create, but not an update 
".write": "!data.exists() || !newData.exists()" 
0

現在.update需要照顧它,你可以改變現有的數據或增加新的一個,而不會影響數據的你已經有了那裏休息。

在這個例子中,我使用這個函數來設置一個產品出售,產品有其他變量的數據,可能或可能沒有soldsellingTime但它並不重要,因爲如果它不存在將創建他們,如果它,將更新數據

var sellingProduct = function(id){ 
dataBase.ref('product/'+id).update({ 
    sold:true, 
    sellingTime: Date.now(), 

}).then (function(){ 
    alert ('your product is flaged as sold') 

}).catch(function(error){ 
    alert ('problem while flaging to sold '+ error) 
}) 

}