2017-08-25 58 views
0

所以我有這個查詢,目前收集所有的數據與materialName等於黃金。我希望所有的改變都是錯誤的。firebase搶orderByChild然後更新結果鍵

// materialName = "gold" for example 
database.ref('/app/posts').orderByChild('material').startAt(materialName).endAt(materialName).once('value', function (snapshot) { 
    const materials = snapshot.val(); 
}) 

我已經試過這樣的事情:

database.ref('/app/posts').orderByChild('material').startAt(materialName).endAt(materialName).once('value', function (snapshot) { 
    database.ref('/app/posts').update({material: false}); 
}) 

我也曾經嘗試這樣做:

const newData = Object.assign({}, materials, {material: false}); 
// but this updates outside of the post, result will be: 


"posts" : { 
     "material": false, 
     "post-1503586" : { 
     "title": "sample title", 
     "material" : "gold" 
     }, 
     "post-9172991" : { 
     "title": "sample title", 
     "material" : "silver" 
     } 
    } 

樣品JSON:

"posts" : { 
     "post-1503586" : { 
     "title": "sample title", 
     "material" : "gold" 
     }, 
     "post-9172991" : { 
     "title": "sample title", 
     "material" : "silver" 
     } 
    } 

回答

2

你需要循環的結果(因爲可以有多個匹配節點S),然後更新每個:

database.ref('/app/posts') 
    .orderByChild('material') 
    .equalTo(materialName) 
    .once('value', function (snapshot) { 
    snapshot.forEach(function(child) { 
     child.ref.update({material: false}); 
    }); 
}); 

您還會注意到,我改變了你的.startAt().endAt()一個equalTo(),這給用更少的代碼相同的結果。