How to have a main child "subscribers" and then inside it a child with an users's uid and then all the uids of users who have subscribed to that user. This way I would store all subscribers of a user and I could easily retrieve them if needed.
{
"subscribers": {
"uid1": {
"uid4": true,
"uid7": true,
"uid3": true
},
"uid15": {
"uid3": true,
"uid9": true,
"uid17": true
},
...
}
}
I don't want to use push() because it generates its own key and if I use setValue() on uid1, then it deletes all its children and ads only the new one, which is also not good. So I want to be able to add and remove subscribers for a certain uid.
SOLUTION:
In my case I was targeting the Android platform, so Java. The solution is based on Dravidian's comment using updateChildren(). Thank you Dravidian.
// ADD SUBSCRIBER
String key = uid; // the uid of the user we want to subscribe to
HashMap<String, Object> subscriber = new HashMap<>();
subscriber.put(subscriberUid, true);
mDatabase.child("subscriptions").child(key).
updateChildren(subscriber, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Log.d(TAG, "Subscribed");
}
});
// REMOVE SUBSCRIBER
mDatabase.child("subscriptions").child(key).child(subscriberUid).removeValue();
// RETRIEVE SUBSCRIBER
mDatabase.child("subscriptions").child(key).
orderByChild(subscriberUid).limitToFirst(1).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "Datasnapshot exists: " + dataSnapshot.exists());
if (dataSnapshot.exists()) {
Log.i(TAG, "User is subscribed");
} else {
Log.i(TAG, "User is not subscribed");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
// ...
}
});