简体   繁体   中英

Non-relational database design confusion

I am learning MongoDB and trying to get my head round the concept of not using a relational database schema.

For my application I want to be able to add new Users and Projects and assign Users to Projects by Roles eg 'manager', 'developer' etc. Users should be able to view details about the Projects in which they have a Role. Retrieving details about a Project should include a list of Users also with Roles in that Project.

Supposing I add a new User via a POST to /users . I can add a new Project with a POST to /projects .

Then I want to give the User a Role in the Project. I could do a PUT to /users/{id} with the Role (including Role name and Project Id) but then retrieving details of a Project via a GET /projects/{id} won't include the list of Users with Roles in that Project.

I could have instead POSTed the Roles to /project/{id} (including Role name and User Id) but then a GET /users/{id} won't include their Roles and I might want to display the Roles a User is involved in on their landing page.

To create a new Role would I really have to PUT it to /users/{id} and then do another PUT to /projects/{id} with the Role and the User?

The above could be achieved in a relational database by simply creating a Roles table which might include the Role name, User Id and Project Id. Then I could perform joins and access whichever information I needed.

Am I missing something here? Any tips or useful references would be greatly appreciated.

I'm afraid you have hit the big downside to NOSQL databases when coming from relational ones. The answer is to forget everything you know about normalisation and to duplicate the data in to both places and then keep them both up to date.

I know this goes against everything you would be taught in a SQL database but that is on of the trade offs. Rob Volk did a good article on this here https://robvolk.com/nosql-design-patterns-for-relational-data-9c2c11ae3b4a

This might seem bad at first but it actually makes sense because what you are basically doing is decreasing read time at the cost of increasing write time and extra memory. Memory is cheap these days and you are going to write user permissions a whole lot less than you are going to read them.

You are right. The NOSql databases has a concept that is not a problem if you repeat the same data along the "tables", since that the repeated information have a hash code, wich will identify a data, that you will use when you want update it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM