Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update all children in Firebase?

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?

like image 465
Petr Mašát Avatar asked Jan 20 '16 10:01

Petr Mašát


People also ask

Can Firebase handle 10 million users?

The limit you're referring to is the limit for the number of concurrently connected users to Firebase Realtime Database on the free Spark plan. Once you upgrade to a payment plan, your project will allow 200,000 simultaneously connected users.

What is getKey () in Firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.


2 Answers

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 accomplish what you need. I'm just not 100% sure what you actually are in need of.

like image 97
Tyler McGinnis Avatar answered Oct 22 '22 02:10

Tyler McGinnis


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 accomplish the same, but the latter send a single command so is more resilient in the case of network failure.

like image 34
Frank van Puffelen Avatar answered Oct 22 '22 01:10

Frank van Puffelen