firebase grab by orderByChild then update results key

烂漫一生 提交于 2020-12-27 05:25:59

问题


So i have this query and currently collects all the data with materialName equals to gold. I wanted change all to false.

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

I have tried something like this:

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

also I have tried this:

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"
      }
    }

sample json:

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

回答1:


You need to loop over the results (since there can be multiple matching nodes) and then update each:

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

You'll also note that I changed your .startAt().endAt() to an equalTo(), which gives the same results with less code.



来源:https://stackoverflow.com/questions/45874969/firebase-grab-by-orderbychild-then-update-results-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!