Search code examples
node.jsdatabasemongodbmongoosemongoose-schema

Best way to store data in a MongoDB


I'm building a site where users can create tasks for other users in their group. Those other users can then respond with answers to those task. My first idea was to have one collection for each type:

  • A user collection with documents that contain the user id as well as the group id.
  • A task collection with documents that contain the task id, user id who created it and the group id.
  • An answer collection with documents that contain the answer id, user id who created it and the task id it is related to.

With this approach everything would be seperate. The problem is that if i need to retrieve each answer for a task for every user in a group. I would have to go through all users and find those which are part of the group, then i need to go through all answers and find those which are A related to the task, and B are created by a user of the group.

The other approach would be to have one big collection that contains a document for every group which each contains all users, which each contains all their tasks which each contains all answers to the task. But i don't like this nested approach because i couldn't easily get all tasks. I also couldn't have users be in two groups.

So basically one modal or multiple modals. What is the best approach here?


Solution

  • I would suggest:

    • group collection with an array for users and an array for tasks
    • user collection with an array for user created tasks, and array of groups they belong to and an array of answers they have given
    • task collection with an array of answers to that task and id of the group the task belongs to
    • answer collection with id of the the task it belongs to and who created it

    MongoDB architecture: how to store a large amount of arrays or sub documents in a scalable way