I would like to make a chat using Firebase. I need to display for each users the list of group they belong to and also for each group all the members.
Because of ho
The data model you have proposed is consistent with recommendations for firebase. A more detailed explanation is outlined in best way to structure data in firebase
users/userid/groups
groups/groupid/users
Firebase provides .transaction for atomic operations. You may chain multiple transactions to ensure data consistency. You may also use onComplete callback function. For detailed explanation refer to firebase transaction. I am using this same approach to keep multiple message counts up to date for a dashboard display.
Sample code for 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
}
})
}
});