Ad

Firebase Organizing Membership To A Document

I'm creating an application in Firebase that needs ensure that users can only read/write documents/collections that belong to their team. My question is basically how should I structure the membership data. Specifically here is one idea I was considering:

/teams/{teamid}
{
   displayName: "Company X Team",
   owner: "userid",
   members: ["email1", "email2", "email3"]
}

/teams/{teamid}/projects/{projectid}
{
    name: "My Project"
    otherProps: "Other Properties"
}

/users/{userid}
{
    displayName: "John Doe",
    email: "[email protected]"
}

Should I store the "members" as an array as part of the /teams/ document (as pictured in the code sample above)? Or should I store it as its own collection of documents, much like the /projects/?

My main concern is when I go and write security rules. I want to make sure only the owner or members are allowed to make changes to /teams/ and its sub collections (like: /projects/).

Which way is going to be easier to write security rules for? Which one will have better performance?

Ad

Answer

I would structure the members as a subcollection instead of an array. Make the document ID of each subcollection member the userID.

Then, you can just write a simple exists() security rule. This would also allow you to store additional data about the membership (are some members admins, when did they join, etc).

match /teams/{teamid}/projects/{projectid} {
      // Make sure a 'user' is a member of the team 
      allow write: if exists(/databases/$(database)/documents/teams/${teamid}/members/$(request.auth.uid))

}

https://firebase.google.com/docs/firestore/security/rules-conditions#access_other_documents

Ad
source: stackoverflow.com
Ad