How to reference collections or atlernatives

I am new to Meteor and MongoDB (just noSQL in general). I’m doing my best to wrap my mind around non-relational data but I’m struggling.

I am trying to build a Project Manager but can’t figure out the best way to associate members to teams. These would be a many-to-many relation in a relational-design.

What is the best way to accomplish this? Or is MongoDB not a good fit?

You can just store _id references like so:

    _id: "u6xnCKNoBgrcvXdTr",
    name: "Alpha Team",
    members: ["MkD2gQWfyeM3bp5Tp", "6jFaLmxNNnKLRArEL"]

Where members contains an array of the userId of users belonging to that team. Now you can look up which teams a user belongs to, by simply querying on the members field (or you can use $elemMatch).

let myTeams = Teams.find({ members: Meteor.userId() }).fetch();

Then if you are accessing this info very often you can make further optimisations using collection-hooks to add/remove teamIds to the user documents that are associated with a particular team when it is created/updated/removed.

1 Like

Thanks for the feedback! I was thinking I would need to supply the user IDs in the team documents as well as team IDs in the user docs.

@zachjohnson also checkout Collection Hooks for de-normalizing data to the other collection(s) automatically. I tend to put those right under where the collection is defined so it’s easy to see what gets saved in one place.

This may be helpful too in some cases: