Empty
Empty

Reputation: 23

Firebase how to add new data to all child

My Firebase Data.

User : {
    user1 : {
         name : 1,
         age : 2
    },
    user2 : {
         name : 1,
         age : 2
    },
      ....
      ....
      ....
   user10 : {
         name : 1,
         age : 2
    }
}

I need add somekey to all user. not use loop each.

userxx : {
      name : 1,
      age : 2,
      somekey : 1
}

current code :

fb.ref("Users").once('value',function(s){
     s.forEach(function(snap){
        fb.ref("Users/"+snap.key+"/somekey").set(2);
     });
});

if small data this code is work, there might be a problem if large data have user 100+ .

thanks and sorry for grammar.

Upvotes: 2

Views: 1277

Answers (1)

Devid Farinelli
Devid Farinelli

Reputation: 7544

Listeners are inexpensive: see this

Anyway in this case you can use multi-path update. Here's an example:

fb.ref("Users").update({
    'user1/somekey': 2,
    'user2/somekey': 2
})

You can probably change your code this way

fb.ref("Users").once('value',function(s){
     var users = s.val()
     var newUsers = {}
     for(var key in users) {
         newUsers[key+'somekey'] = 2
     }
     fb.ref("Users").update(newUsers)
});

Hope it helps ;)

Upvotes: 2

Related Questions