Search code examples
mongodbmany-to-manynosql

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:

  • query for all users in the db, reading their role data, too;
  • query for all roles just available in the db, for example, for choosing the role associated in user creation;

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?


Solution

  • Your options are:

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

    Make your choice...