0

I am trying to come up with some sort of a solution to keep a count of a node with many child nodes... I thought of just keeping a field and increment it as stuff is added to the parent node

My one concern is multiple users adding to the node at the same time, is there a way I could safely incriment without worrying about overrighting if other users icriment the count at the same time


Thanks to @FrankVanPuffelen for pointing me in the right direction.. How exactly would you go about callling it for a simple counter? Heres what I wrote up but dosen't seem to be working the way I expected

var ref = firebase().database().ref('Counter');

export function toggleStar(postRef) {
  postRef.transaction(function(post) {
    if (post) {
      post++;
    }else{
      post = 0;
    }
    return post;
  });
}

//then to Call it:
toggleStar(ref);

Tried to keep it minimal so it could help someone else trying to implement a counter system. The field Counter in this case would just be my spot where I would like to store it. I tried to add a case where if it was false or NULL to set it to 0.

EDIT 2: Also did this:

export function toggleStar(postRef) {
  postRef.transaction(function(post) {
    if (post) {
      post.go++;
    }else{
      post = {};
      post.go = 0;
    }
    return post;
  });
}

ANd called ti with the same method above. This does appear to be working... However I am worried that this isn't accomplishing the process in the right way so I just want to be sure... I don't want to overwrite other users data and having inaccurate numbers

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Joe Caraccio
  • 1,899
  • 3
  • 24
  • 41
  • 1
    You could accomplish that with a transaction. See the documentation here: https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions. – Frank van Puffelen Jan 01 '17 at 07:07
  • @FrankvanPuffelen Thanks for pointing me in the right direction. I attempted to use it above.. could you see my attempt and perhaps try to point me in the right direction? Tried to keep it minimal so others could utilize it.. Thanks so much! – Joe Caraccio Jan 01 '17 at 14:00
  • Firebase has recently release Cloud Functions. Have a look at this [answer](http://stackoverflow.com/a/42713792/5861618) for more details – Rosário Pereira Fernandes Mar 10 '17 at 08:54

0 Answers0