Reputation: 11039
I have collections Project
, Group
, and Item
. An item belongs to a group and a group belongs to a project.
The items are often updated, so they have to be in a separate collection but the groups are almost always created with the project. So I wonder if it's better to create a project schema which looks something like:
Project {
'id': String,
'name': String,
'groups': {
{
'id': String,
'total_amount': Number
}
},
total_amount: Number
}
But I need to print total_amount both on the project and in each group. I guess it is not possible to use annotated querysets to create these sums since MongoDB does not support relational schemas. So I guess I have to update the total_amount
field every time the amount
field in a Item
document is updated.
How can I make sure the total_amount
in Project
and Group
is updated to reflect the total sum of the amounts in the items which belong to those projects/groups? Will the proposed schema above fit my needs? I don't think it's a big problem to imitate a relational schema using Item.groupId
and Group.projectId
but I'm not sure what to do about the totals.
I could also create a template helper which loops through the children and sum the total. But I guess it's quite memory consuming to loop through all objects every time the page is loaded.
Upvotes: 1
Views: 58
Reputation: 4081
A solid rule is that if groups
are usually needed in the context of projects
, then embedding groups
in projects
is the best solution.
Now, about total_amount
: Since groups can not be shared between projects, I believe updating total_amount
every time an item changes is totally fine. If your app is small and items
are not updated super-often, there's nothing wrong with this (it essentially only adds 1 write operation).
Upvotes: 1