how to structure many-to-many relationships in mongoose? how to structure many-to-many relationships in mongoose? mongoose mongoose

how to structure many-to-many relationships in mongoose?


In mongodb, you have two choices. Embedding (subdocument) Vs Linking (another collection)

Embedding Vs LinkingThere are pros and cons with each approach.

Embedding:You nest it inside the document.

for instance, your document might look like

{    name : 'name',    events: [a,b,c],    groups: [1,2,3]}
  • you get atomicity, since only one collection is involved.
  • however, values might be duplicated

Linking

Here you link with a kind of Foreign key. Refer to docs

Documents in one collection will reference documents in another collection. Disadvantage is that you lose atomic operations. However, you eliminate duplication.

If you want to update groups, and update events, and they are in separate collections, you'll have to handle atomic updates yourself. Mongodb will not guarantee it for you.