通过orderByChild进行firebase抓取,然后更新结果键 [英] firebase grab by orderByChild then update results key

查看:36
本文介绍了通过orderByChild进行firebase抓取,然后更新结果键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有此查询,当前收集的所有数据的 materialName 等于黄金.我想将所有内容更改为false.

 //materialName ="gold"例如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});//,但此更新在帖子之外,结果将是:帖子":{材料":假,"post-1503586":{"title":样本标题",材料":金"},"post-9172991":{"title":样本标题",材料":银"}} 

样本json:

 帖子":{"post-1503586":{"title":样本标题",材料":金"},"post-9172991":{"title":样本标题",材料":银"}} 

解决方案

您需要遍历结果(因为可以有多个匹配的节点),然后更新每个结点:

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

您还将注意到,我将您的 .startAt().endAt()更改为 Toal(),从而以更少的代码获得了相同的结果./p>

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

解决方案

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.

这篇关于通过orderByChild进行firebase抓取,然后更新结果键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆