How to store users and groups in chat using Firebase

I would like to talk with Firebase. I need to display for each user a list of the group to which they belong, as well as for each group of all members.

Due to the fact that Firebase is designed, and in order to have acceptable performance, I think by creating a list of all groups containing a list of members, and for each user, an entry with the entire group in which they belong.

My first question is: is it right?

If so, then my second question is how can I atomize (or delete) the user, i.e. make sure that the user is added to the group, and the group is added to the user or not added at all (i.e. is never stored in 1 and make the database inconsistent)?

+5
source share
1 answer

The proposed data model complies with the recommendations for firebase. A more detailed explanation is given in the best way to structure data in firebase .

users/userid/groups groups/groupid/users 

Firebase provides .transaction for atomic operations. You can bind multiple transactions to ensure data consistency. You can also use the onComplete callback function. A detailed explanation can be found in firebase transaction . I use the same approach to update the display of multiple messages to display the panel.

Sample code for a nested transaction:

 ref.child('users').child(userid).child(groupid).transaction(function (currentData) { if (currentData === null) { return groupid; } else { console.log('groupid already exists.'); return; // Abort the transaction. } }, function (error, committed, snapshot) { if (committed) { console.log('start a new transaction'); ref.child('groups').child(groupid).child(userid).tranaction(function (currentData) { if (currentData === null) { return userid; } else { console.log('Userid already exists.'); //add code here to roll back the groupid added to users return; // Abort the transaction. } }, function (error, committed, snapshot) { if (error) { //rollback the groupid that was added to users in previous transaction } }) } }); 
+2
source

All Articles