3
votes

I can't figure out how to solve this issue with firebase : I have users, each user has posts, each post has an id generated by firebase, how can I store these ids in a user node ?

I'm using string,concatenating them, parsing them in my js app. Basically treating them as a csv file. But i guess that's a very ugly solution

What would be the way to store this kind of data ?

Edit:

UserID :

  • Username = "User Name"
  • Posts = "id1,id2,id3,id4"

When a user has a new post, I use a transaction to append a new id at the end of the string. When I need to delete an id, again I use a transaction and I delete the element using this code:

removeElem(list, value) {
var separator = ",";
var values = list.split(separator);
for (var i = 0; i < values.length; i++) {
    if (values[i] == value) {
        values.splice(i, 1);
        return values.join(separator);
    }
}
return list;
},
1
Instead of describing your data structure and code, show it. Provide a minimal, complete, compilable example that reproduces what you are asking about. Then say what your concerns are, because "ugly" is very subjective. What you consider ugly, I might consider "it works, so it's beautiful". - Frank van Puffelen
I edited my post and added some infos. - Faton Ramadani
Answer below. As quite often, this is mostly a copy of the relevant snippet of the Firebase guide for JavaScript developers. I highly recommend reading that guide cover-to-cover today. A few hours spent there now, will save much more time (and many questions) down the line. - Frank van Puffelen

1 Answers

3
votes

While transactions will work for this, it seriously hurts scalability and will not work at all when the user temporarily loses connectivity. For a better solution, get rid of the array logic and use Firebase's push() method. From the Firebase documentation on saving lists of data:

Push vs Transaction

When working with lists of data push() ensures a unique and chronological ID. You may be tempted to use transactions instead to generate your own IDs, but push is a far better choice. Transactions are slower and more complex. They require one or more round trips to the server. A push ID can be generated on the client will work while offline and is optimized for performance.

While it may take some getting used to the non-sequential keys, it's going to be better in the long run.