Fabio B.
Fabio B.

Reputation: 9400

Something I don't understand about NoSQL (M:N relationships)

I admit it... I lack a lot of theory concepts when it comes to NoSQL world.

I was thinking about porting some simple apps using Java+MySQL to NodeJS+MongoDB (I found the mongoose ORM which looks really cool).

One of the first thing I find really hard and less documented is mapping many-to-many relationships.

I first read the Mongo-DOCS: http://www.mongodb.org/display/DOCS/Schema+Design

... then lurked around for some real-world info, and I found lots of q&a like that: Modeling data on a many-to-many join in Mongo?

There's the way to achieve a M:N, cool! But then I read something that really scares and disappoint me: " Honestly I would just go with a relational database if you find yourself needing joins. "

OK! I get the point but.... imagine I have the common User + Roles + UserRoles many-to-many schema and I use embedding, I mean, I do not use another table-schema for roles, I only use User with all roles data in it

I need to:

The first point is trivial, but what about the second?

You will tell me that I need another table-schema "Roles" and store in "User" the roles array, with IDs of roles but then, you will tell me that this is a relational world!

Are you tellin' me that it's not suitable for a NoSQL db? So what would be?

Upvotes: 4

Views: 748

Answers (2)

Venemo
Venemo

Reputation: 19097

You may need to denormalize your data.

The way to do it correctly is to look at your use cases and design your database accordingly.
This means that you will have to think about the usage scenarios.

The users/roles example

Let's think about the use cases.

  • Quickly tell what roles are a user in
  • Query all the roles so that you can pick roles for a user when you create or edit a user.

I would do it like this:

  • Store the roles on the users as you do now
  • Also store all the roles in a separate collection

This will fulfill all the requirements correctly.
Obviously, because of the denormalization, you will need to take special care when updating/renaming the roles.

Upvotes: 3

user2665694
user2665694

Reputation:

Your options are:

  • denormalize your data
  • perform multiple queries
  • use the MongoDB aggregation framework (if applicable here)
  • don't use MongoDB

Make your choice...

Upvotes: 0

Related Questions