简体   繁体   中英

Sum field in children objects in Meteor

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.

Edit

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM