问题
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:
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.
来源:https://stackoverflow.com/questions/36679621/storing-a-list-of-ids-in-firebase