Ad

How Can I Segregate User Data In Firebase?

I'm creating an app that has uses a firebase Cloud Firestore database. The structure seems to be collection/document/fields. I am thinking of either using the user id as the prefix to the collection name or simply a field for userId.

I'm currently using:

Firestore.firestore().collection("Events").  

This could be changed to prefix event with the userId

I am currently reading everything in using:

reference(to: "Events").addSnapshotListener{ (snapshot, _) in
    guard let snapshot = snapshot else {return}
    for document in snapshot.documents {
        // code here
    }
}
Ad

Answer

It's not a really good idea to use prefixes on collection names. That doesn't work well with security rules.

The usual structure for per-user data is to have a collection with documents whose IDs are the user IDs. Then, you can further organize other data in subcollections under that document ID.

/users
  /uid1
  /uid2
    /events
    /likes
    /history

Then, you can write security rules using the user's UID very easily.

Ad
source: stackoverflow.com
Ad