Chris F.
Chris F.

Reputation: 501

What is best practice for modeling a SaaS app with Firebase on a many-to-many relationship

I have two collections: an org and a user. A user can be a regular user of org A but can also be an admin of org B. So the user collection would look something like this:

{
email: "[email protected]",
name: "John Doe",
access: [
    {
        org: "orgA",
        role: "user"
    },
    {
        org: "orgB",
        role: "admin"
    }
]}

The problem with keeping everything in the same collection is that I do not like admins of org A to update the access array and impact org B. If I move the access array in a sub-collection under the /user collection when showing the list of users for each collection, I'd have to make a call for each user to get the access info. Should I save the user IDs in an array in a sub-collection under the /org collection?

I guess my goal is to find a best practice solution for this problem.

Upvotes: 0

Views: 309

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138834

The simplest database structure I can think of would be:

Firestore-root
   |
   --- users (collection)
   |    |
   |    --- $uid (document)
   |         |
   |         --- email: "[email protected]"
   |         |
   |         --- name: "John Doe"
   |         |
   |         --- userOf (map)
   |         |     |
   |         |     --- orgA: true
   |         |
   |         --- adminOf (map)
   |               |
   |               --- orgB: true
   |
   --- organizations (collection)
        |
        --- $orgA (document)
        |    |
        |    --- users: ["uidOne", "uidTwo"] (array)
        |
        --- $orgB (document)
             |
             --- admins: ["uidThree", "uidFour"] (array)

In this way, you can simply query the "users" collection to get regular users of some organization, as well as admin, or even both.

Upvotes: 3

Jacopo Bonomi
Jacopo Bonomi

Reputation: 458

You have two approaches, one is insert a key of access in user, and the same in access. Otherwise you can use a Junction table, with the id of both. There is no exact answer, with the right safety rules and for performance is practically the same. Then decide based on the approach you feel is most appropriate for you design.

Upvotes: 1

Related Questions