最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to update all children in Firebase? - Stack Overflow

programmeradmin7浏览0评论

I'm try on firebase update all child on one level of tree. For example something like this:

firebase.child("auctions").child().update({a: true});

and this give me back error, because child is empty. Are there any way how update all children of auctions?

I'm try on firebase update all child on one level of tree. For example something like this:

firebase.child("auctions").child().update({a: true});

and this give me back error, because child is empty. Are there any way how update all children of auctions?

Share Improve this question edited Jan 20, 2016 at 15:16 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges asked Jan 20, 2016 at 10:33 Petr MašátPetr Mašát 5351 gold badge5 silver badges7 bronze badges 1
  • for clear understand, i've got this structure auctions->item1->a->true` and item i've got more than one. Are there any way how make change for all a? Thank's – Petr Mašát Commented Jan 20, 2016 at 12:28
Add a ment  | 

2 Answers 2

Reset to default 3

You don't need that empty .child() invocation.

What firebase.child("auctions").update({a: true}); is going to do is change /auctions/a/whatever to /auctions/a/true.

If you really want to "update all child on one level of tree" then .set might work better since it will replace all the data at the endpoint with the object you give it. So if you ran firebase.child("auctions").set({a: true}); then everything under /auctions will be replaced with {a: true}

If you didn't want to blast away everything under /auctions but instead you wanted to blast away everything under auctions/a you could do firebase.child("auctions/a").set(true);

There are multiple ways to acplish what you need. I'm just not 100% sure what you actually are in need of.

You will need to loop over all children at some point. Here's one simple way to do this:

firebase.child("auctions").on('value', function(snapshot) {
    snapshot.ref().update({a: true}); // or snapshot.ref if you're in SDK 3.0 or higher
});

Alternatively you can first collect all updates and then send them to Firebase as one (potentially big) update statement:

var updates = {};
firebase.child("auctions").on('value', function(snapshot) {
    updates["auctions/"+snapshot.key+"/a"] = true;
});
snapshot.ref().update(updates);  // or snapshot.ref if you're in SDK 3.0 or higher

Both snippets acplish the same, but the latter send a single mand so is more resilient in the case of network failure.

发布评论

评论列表(0)

  1. 暂无评论