test
test

Reputation: 2466

firebase grab by orderByChild then update results key

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

Upvotes: 0

Views: 1281

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

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.

Upvotes: 5

Related Questions