NoSQL & Firebase: Storing & Iterating over many-to

2019-09-11 13:33发布

I have 2 main nodes in my database: Users and Projects.

Each user can be assigned to multiple projects, in different roles.

After reading about how to structure many to many relationship, I ended up that it should look like this:

users : {
  user1 : {
    name : blah,
    email : a@a.com,
    projects : {
      projects1key : true,
      projects2key : true
    }
  }
}

projects : {
  project1key : {
    name : blahserve,
    category : blahbers,
    providers : {
      user1 : true,
      user7 : true
    }
  }
}

What I couldn't figure out is how I can assign every user a role in each project.

  1. What's the new database structure should look like if I need to add role (string) to each user within a project?

  2. Correct me if I'm wrong: When I assign user to a project, I need to create 2 new nodes: a projectkey node in my user node, and a userkey node in my projectkeynode. Is that right?

Update

Since the answer given here is correct but not sure it will fit my use case, this is my use case:

  • (1) Iterating over a list of all project users
  • (2) Iterating over a list of all member project
  • (3) Check for project role when the user access a project and give give him permission depends on his role
  • (4) The "Project -> users" page allow you to add a new user to existing project. the user role is picked in the same form together with the user. the user must have a role in a project.

1条回答
神经病院院长
2楼-- · 2019-09-11 13:48

Or maybe just simply you could add a different node all together:-

What's the new database structure should look like if I need to add role (string) to each user within a project?

users : {
 user1 : {
  name : blah,
  email : a@a.com,
    }
  },

projects : {
  projectKey1 : {
    name : blahserve,
    category : blahbers,
    }
},

projectsLists:{

  user1 :{
    projectKey1 : true,
    projectKey2 : true 
    }
}, 

projectsRoles :{

  projectKey1 : {
     user1 : provider,
     user2 : editor,
     ....
    }
  }

Correct me if I'm wrong: When I assign user to a project, I need to create 2 new nodes: a projectkey node in my user node, and a userkey node in my projectkeynode. Is that right?

Always prefer the flatter DB structure. So using this structure you only gotta append or update your user's role once.

查看更多
登录 后发表回答